Constructor chaining example program in same class using this keyword.


  1. package instanceofjava;
  2. class ConstructorChaining{
  3. int a,b 
  4. ConstructorChaining(){
  5. this(1,2);
  6.  System.out.println("Default constructor");
  7.  
  8.  
  9. ConstructorChaining(int x , int y){
  10.  
  11. this(1,2,3); 
  12. a=x;
  13. b=y;
  14.  System.out.println("Two argument constructor");
  15.  
  16. }
  17.  
  18. ConstructorChaining(int a , int b,int c){
  19.  System.out.println("Three argument constructor")
  20.  
  21. public static void main(String[] args){
  22.  
  23.  ConstructorChaining obj=new ConstructorChaining();
  24.   System.out.println(obj.a);
  25.   System.out.println(obj.b);
  26.  
  27. }
  28. }


Output:

  1. Three argument constructor
  2. Two argument constructor
  3. Default argument constructor
  4. 1
  5. 2

Constructor chaining example program in same class using this and super keywords.

  1. package instanceofjava;
  2. class SuperClass{
  3.  
  4. SuperClass(){
  5. this(1);
  6.  System.out.println("Super Class no-argument constructor");
  7.  
  8.  
  9. SuperClass(int x ){
  10.  
  11. this(1,"constructor chaining"); 
  12. System.out.println("Super class one -argument constructor(int)");
  13.  
  14. }
  15.  
  16. SuperClass(int x , String str){
  17.  System.out.println("Super class two-argument constructor(int, String)");
  18.  
  19. }




  1. package instanceofjava;
  2. class SubClass extends SuperClass{

  3. SubClass(){
  4. this(1);
  5.  System.out.println("Sub Class no-argument constructor");
  6.  
  7.  
  8. SubClass(int x ){
  9.  
  10. this("Constructor chaining"); 
  11.  System.out.println("Sub class integer argument constructor");
  12.  
  13. }
  14.  
  15. ConstructorChaining(String str){
  16. //here by default super() call will be there so it will call super class constructor
  17.   System.out.println("Sub class String argument constructor");
  18.  
  19. public static void main(String[] args){
  20.  
  21.  SubClass obj=new SubClass();
  22.  
  23.  
  24. }
  25. }

Output:

  1. Super class two-argument constructor(int, String)
  2. Super class one -argument constructor(int)
  3. Super Class no-argument constructor
  4. Sub class String argument constructor
  5. Sub class String argument constructor
  6. Sub class integer argument constructor




Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

1 comments for Constructor chaining in java using this and super Keywords

  1. In your SubClass Constructor of String it the constructor name is wrong. Kindly correct it.

    ReplyDelete

Select Menu