How to call another constructor from a constructor in JAVA?
3511 Views
Hints
super() - super is used to call constructor of super class or extended class.
this() - this method is used to call the constructor of the same class from another constructor.
this() and super() methods can call only in constructor and should be the first statement.
Example
class Cricket {
int runs;
int over;
public Cricket(){
over = 99;
}
public Cricket(int runs){
//Call with parameters using this(10,20);
this();
this.runs = runs;
}
public void display(){
System.out.println("Runs: "+runs+";Over: "+over);
}
}
class Solution {
public static void main(String args[])throws Exception{
Cricket cric = new Cricket(10);
cric.display();
}
}