Any constructor in subclass will call the no argument contructor(or default constructor) of parent class. if you define a parameterized constructor in parent class then you have to explicitly call the parent class constructor with super keyword else it will give the 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 give the 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 no argument constructor/default constructor in parent class nor we are calling the parameterized constructor from sub class.
Now to solve this either call the parameterized constructor like this:
class Alpha
{
Alpha(int s, int p)
{
System.out.println("base");
}
}
public class SubAlpha extends Alpha
{
SubAlpha()
{
super(4, 5); // calling the parameterized constructor of parent class
System.out.println("derived");
}
public static void main(String[] args)
{
new SubAlpha();
}
}
Output
base
derived
or
define a no argument constructor in parent class like this:
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();
}
}
output
derived