Exercise:
Write a Java Program to call super-class constructor from child class constructor.
Click Here to View the Solution!
class CallConstructor {
// constructor of the superclass
CallConstructor (int number1, int number2) {
if (number1 > number2) {
System.out.println("The greater number is: " + number1);
}
else {
System.out.println("The greater number is: " + number2);
}
}
}
// child class
public class Child extends CallConstructor {
// constructor
Child() {
// calling super class’s constructor
super(29, 16);
}
// main method
public static void main(String[] args)
// calling child class constructor
Child obj = new Child();
}
}
Click Here to View the Output!
The greater number is: 29
Click Here to View the Explanation!
- This program is used to call the constructor of the superclass through the constructor of the child class.
- A super class C
allConstructor
is created that holds the parameters as(int number1, int number2)
and finds the latest version through if…else statement. - Another class, subclass
Child
is created that calls the constructor of the superclass from its constructor usingsuper(29, 16)
. - By creating an object in the main method , the superclass constructor
CallConstructor(int number1, int number2)
is called from the subclass constructor and the latest version is printed on the screen.