Have you ever wonder can we call super class constructor from subclass?It is possible with the keyword super.
Super keyword has two uses.
- The first is the call to the super class constructor from subclass constructor
- The second usage is to access a member of the superclass that has been overridden by a subclass
- A subclass constructor can call a constructor defined in its immediate superclass by employing the following form of super:
- super( parameter list);
Here parameter list specifies any parameters needed by the constructor in the superclass.
Using super to call superclass constructors
- super() must always be the first statement executed inside a subclass constructor.
- It clearly tells you the order of invocation of constructors in a class hierarchy.
- Constructors are invoked in the order of their derivation.
- A more efficient and robust definition of the superclass RectangularSolid class and the corresponding changes in the subclass RectangularSolidWeight follows.
class RectangularSolid{
private double width;
private double height;
private double depth;
RectangularSolid(double w,double h,double d)
{
width=w;
height=h;
depth=d;
}
RectangularSolid(double length)
{
width=height=depth=length;
}
RectangularSolid()
{
width=height=depth=10;
}
double volume(){
return width*height*depth;
}
}
class RectangularSolidWeight extends RectangularSolid
{
double weight;
public RectangularSolidWeight(double w,double h, double d,double wt)
{
super(w,h,d);
weight = wt;
}
public RectangularSolidWeight(double len,double wt)
{
super(len);
weight = wt;
}
public RectangularSolidWeight()
{
super();
weight =0;
}
}
class SuperDemo
{
public static void main(String[] args)
{
RectangularSolidWeight rsw1 = new RectangularSolidWeight(4,5,7,8.0);
RectangularSolidWeight rsw2 = new RectangularSolidWeight();
RectangularSolidWeight rswcube = new RectangularSolidWeight(3,2);
double volume;
volume = rsw1.volume();
System.out.println("Volume of rsw1 is"+volume);
System.out.println("weight of rsw1 is"+rsw1.weight);
System.out.println();
volume = rsw2.volume();
System.out.println("Volume of rsw2 is"+volume);
System.out.println("weight of rsw2 is"+rsw2.weight);
System.out.println();
volume = rswcube.volume();
System.out.println("Volume of rswcube is"+volume);
System.out.println("weight of rswcube is"+rswcube.weight);
System.out.println();
}
}
Output:
Volume of rsw1 is140.0
weight of rsw1 is8.0
Volume of rsw2 is1000.0
weight of rsw2 is0.0
Volume of rswcube is27.0
weight of rswcube is2.0
The superclass constructor is invoked first followed by the invocation of the subclass constructor.
- When a subclass calls super(),it is calling the constructor of it immediate superclass
- This is true even in a multileveled hierarchy
- super() must always be the first statement inside s subclass constructor.
