| Author |
Constructor Overloading
|
abhinas raj
Ranch Hand
Joined: Jun 02, 2012
Posts: 43
|
|
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
Joined: Aug 31, 2007
Posts: 774
|
|
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.
|
SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
|
 |
abhinas raj
Ranch Hand
Joined: Jun 02, 2012
Posts: 43
|
|
|
yaa got it thanks .
|
 |
 |
|
|
subject: Constructor Overloading
|
|
|