Knowledge Walls
John Peter
Pune, Maharashtra, India
How to call another constructor from a constructor in JAVA?
3486 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();
    }
}
Output 
Runs: 10;Over: 99
Previous Topics
Previous lessons of current book.
Computer software engineer articles of One day One Thing to Know
Best Lessons of "One day One Thing to Know"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details