English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to call another constructor from a constructor in Java.
To understand this example, you should understand the followingJava programmingTopic:
class Main { int sum; //First constructor Main() { //Call the second constructor this(5, 2); } //Second constructor Main(int arg1, int arg2) { //Add two values this.sum = arg1 + arg2; } void display() { System.out.println("Total: ") + sum); } // main class public static void main(String[] args) { // Calling the first constructor Main obj = new Main(); // Call the display method obj.display(); } }
Output Result
Total: 7
In the above example, we created a class named Main. Here, you created two constructors within the Main class.
Main() {..} Main(int arg1, int arg2) {...}
In the first constructor, we used the this keyword to call the second constructor.
this(5, 2);
Here, by passing parameters 5 And 2 Calling the second constructor from the first constructor.
Note: The line calling another constructor in the constructor should be the first line of that constructor. That is, this(5, 2) should be the first line of Main().
We can also use super(), to call the superclass constructor from the subclass constructor.
// Superclass class Languages { //Superclass constructor Languages(int version1, int version2) { if (version1 > version2) { System.out.println("Latest version is: " + version1); } else { System.out.println("Latest version is: " + version2); } } } //Subclass class Main extends Languages { //Subclass constructor Main() { //Calling the superclass constructor lass super(11, 8); } // main method public static void main(String[] args) { // Calling the first constructor Main obj = new Main(); } }
Output Result
Latest version is: 11
In the above example, we create a superclass named Languages and a Main subclass. Please note the following line in the constructor of the Main class:
super(11, 8);
Here, we call the superclass constructor (i.e., Languages(int version1, int version2)