Thursday, 18 June 2015

Can you call one constructor from another? 

 Yes, by using this() syntax.  

EX: 1

public Pet(int id) { 

this.id = id; // “this” means this object 

}

 public Pet (int id, String type) { 

this(id);       // calls constructor public Pet(int id) this.type = type;

 // ”this” means this bject 

}

 EX: 2

 class Rectangle{   

int length,breadth;   

void show(int length,int breadth){  

 this.length=length; 

  this.breadth=breadth;  

 }   

int calculate(){   

return(length*breadth);   }

 }

 public class UseOfThisOperator{ 

  public static void main(String[] args){   

Rectangle rectangle=new Rectangle();  

 rectangle.show(5,6);   

int area = rectangle.calculate();  

 System.out.println("The area of a Rectangle is  :  " + area);  

 }

 }

 

 

What is the use of “this”? 

1.     To specifically denote that the instance variable is used instead of static or local varible. That is, 

private String javaThis;

void methodName(String javaThis) {

this. javaThis = javaThis;

 }

2.     This is used to refer the constructors .

public JavaQuestions(String javapapers) {

 this(javapapers, true);

} 

3.      This is used to pass the current java instance as parameter obj.itIsMe(this);

4.     Similar to the above this can also be used to return the current instance

 CurrentClassName startMethod() {

return this;

} 

5.     This can be used to get the handle of the current class 

Class className = this.getClass(); // this methodology is preferable in java   How to call the superclass constructor?  If a class called “Special Pet” extends your “Pet” class then you can Use the keyword “super” to invoke the super class’s constructor.  

Ex: 

public SpecialPet(int id) { 

super(id); //must be the very first statement in the constructor. 

} 

Both super()and this() can’t be used in same constructor at a time. 

Ex : 

B(int a ,int b) {  

 Super(a);   

This(); 


} //Compilation error This() is for only constructors not for methods.

No comments:

Post a Comment