Users Online

· Guests Online: 110

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

009 Java Constructor Chaining with example

Java – Constructor Chaining with example

Calling a constructor from the another constructor of same class is known as Constructor chaining. We will understand this with the help of below program.

Example Program

In the below example the class “ChainingDemo” has 4 constructors and we are calling one constructor from another using this() statement. For e.g. in order to call a constructor with single string argument we have supplied a string in this() statement like this(“hello”).

Note: this() should always be the first statement in constructor otherwise you will get the below error message:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Constructor call must be the first statement in a constructor

Complete Code:

package beginnersbook.com;
public class ChainingDemo {
   //default constructor of the class
   public ChainingDemo(){
         System.out.println("Default constructor");
   }
   public ChainingDemo(String str){
         this();
    	 System.out.println("Parametrized constructor with single param");
   }
   public ChainingDemo(String str, int num){
         //It will call the constructor with String argument
    	 this("Hello"); 
    	 System.out.println("Parametrized constructor with double args");
   }
   public ChainingDemo(int num1, int num2, int num3){
   	// It will call the constructor with (String, integer) arguments
        this("Hello", 2);
        System.out.println("Parametrized constructor with three args");
   }
   public static void main(String args[]){
        //Creating an object using Constructor with 3 int arguments
        ChainingDemo obj = new ChainingDemo(5,5,15);
   }
}

Output:

Default constructor
Parametrized constructor with single param
Parametrized constructor with double args
Parametrized constructor with three args

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 0.74 seconds
10,258,898 unique visits