Two Laptop Bag
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructor Overloading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructor Overloading" Watch "Constructor Overloading" New topic

Constructor Overloading

abhinas raj
Ranch Hand

Joined: Jun 02, 2012
Posts: 47
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){
System.out.println("--- Xyz(int, String) --\t:"+this.value+"\t:"+this.msg);
System.out.println("--- Xyz(int, String) --\t:"+this.value+"\t:"+this.msg);

class Person{
int age;
String name;

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

class User extends Person{
String uname;
String pwd;

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

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


class Employee extends User{
int eid;
String email;

System.out.println("-- Employee() cons--\t:"+this);

Ninad Kulkarni
Ranch Hand

Joined: Aug 31, 2007
Posts: 802

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: 47
yaa got it thanks .
I agree. Here's the link:
subject: Constructor Overloading
It's not a secret anymore!