Calling more than one constructor of same class with SINGLE instance in java…

Hi Friends

Can we call more than one constructor of same class with single instance ?

Yes, why not ? use this keyword…

Here is the demo…

class MyClass{
public MyClass() {
this(1); // here it will call one parameterized constructor of this class
System.out.println(“This is Zero parameter constructor”);
}public MyClass(int a){
this(1,2); // here it will call two parameterized constructor of this class
System.out.println(“This is One parameterized constructor”);
}

public MyClass(int a, int b){
System.out.println(“This is Two parameterized constructor”);
}

public static void main(String[] args) {

// As we have created only one instance
MyClass m1 = new MyClass();
}
}

output is :

This is Two parameterized constructor
This is One parameterized constructor
This is Zero parameter constructor

Here, we have created three constructor in a same class and first invoking zero parameterized constructor.

Then calling one parameterized constructor inside from zero parameterized, with the help of “this(1)”

and, then  calling two parameterized constructor inside from one parameterized, with the help of “this(1,2)”

So, with the help of this keyword, we can call current class constructor…

Advertisements

2 thoughts on “Calling more than one constructor of same class with SINGLE instance in java…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s