Monday, 18 March 2019

Core Java: This() and this

package StudyPackage;

public class ThisKeyword {

//Default Constructor
ThisKeyword(){
this(5);
System.out.println("Default Constructor");
}

//Constructor with 1 parameter
ThisKeyword(int data){
this(5,6);
System.out.println("Int Constructor");
}

//Constructor with 2 parameters
ThisKeyword(int data,int data1){
System.out.println("Int Constructor with 2 Arguments");

}
  public static void main(String[] args) {

  ThisKeyword th=new ThisKeyword();//Calling Default
  //  
}
}

OutPut:
Int Constructor with 2 Arguments
Int Constructor
Default Constructor

#this() is useful for calling the constructor. Matching constructors gets called based on parameters provided.

#Should be first line in constructor. 2 this() not allowed


No comments:

Post a Comment

Spring Boot : Exception Handler 14