Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor Overloading

 
abhinas raj
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in the following program when i call Users's class argumented constructor new User("JLC","JLC"); then why User class default constructor has been called ? as i am calling this(); keyword . constructor call inside a constructor should be the first statement so why it is invoking super() and this() both, i mean when i run this program it gives the output like

--Person() cons -- :User@43f854bd
-- User() cons -- :User@43f854bd
-- User(String,String) cons -- :User@43f854bd

corresponding to the call new User("JLC","JLC"); bellow is the complete code


------------------------------------------------------------------------------------------------

class L_23_60_Superkeyword{
public static void main(String args[]){

Xyz ref=new Xyz(99,"JLC");

new Person();

new User();

new User("JLC","JLC");


new Employee();

}}

class Xyz{

int value;
String msg;

Xyz(int value, String msg){
super();
System.out.println("--- Xyz(int, String) --\t:"+this.value+"\t:"+this.msg);
this.value=value;
this.msg=msg;
System.out.println("--- Xyz(int, String) --\t:"+this.value+"\t:"+this.msg);
System.out.println();
}
}

class Person{
int age;
String name;

Person(){
System.out.println("--Person() cons --\t:"+this);
}
}

class User extends Person{
String uname;
String pwd;

User(){
System.out.println("-- User() cons --\t:"+this);
}

// why User's default constructor has been called ?
User(String uname, String pwd){
this();
System.out.println("-- User(String,String) cons --\t:"+this);
}

}

class Employee extends User{
int eid;
String email;

Employee(){
System.out.println("-- Employee() cons--\t:"+this);
System.out.println(age+"\t"+name+"\t"+uname+"\t"+pwd+"\t"+eid+"\t"+email);
}

}
 
Ninad Kulkarni
Ranch Hand
Posts: 802
Hibernate Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Abhinas,
When new User("JLC","JLC"); statement executed following things happen

1 this() will call no argument constructor User()
2 no argument constructor User() will call super() which in turn call Person()
3 now Person() will call super() that is constructor of Object class and then person body will complete the execution then User() body will complete the execution then User(String , String) body will complete the execution.

I hope this will help you to understand. In case of any mistake please let me know.
 
abhinas raj
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yaa got it thanks .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic