Any constructor in a subclass will invoke the constructor without arguments (or the default constructor) of the parent class. if you define a parameterized constructor in the parent class, then you have to explicitly call the constructor of the parent class using the super keyword, otherwise this will cause a compilation error.
class Alpha { Alpha(int s, int p) { System.out.println("base"); } } public class SubAlpha extends Alpha { SubAlpha() { System.out.println("derived"); } public static void main(String[] args) { new SubAlpha(); } }
The above code will throw a compilation error:
prog.java:13: error: constructor Alpha in class Alpha cannot be applied to given types; { ^ required: int,int found: no arguments reason: actual and formal argument lists differ in length 1 error
The above error occurred because neither we have any argument constructor / default constructor in the parent class, nor do we call the parameterized constructor from the subclass.
Now, to solve this, either call a parameterized constructor, for example like this:
class Alpha { Alpha(int s, int p) { System.out.println("base"); } } public class SubAlpha extends Alpha { SubAlpha() { super(4, 5);
Exit
base derived
or
define a constructor with no arguments in the parent class as follows:
class Alpha { Alpha(){ } Alpha(int s, int p) { System.out.println("base"); } } public class SubAlpha extends Alpha { SubAlpha() { System.out.println("derived"); } public static void main(String[] args) { new SubAlpha(); } }
exit
derived
Anmol Middha May 19 '19 at 7:47 a.m. 2019-05-19 07:47
source share