by Dinesh Thakur

A subclass inherits the accessible data fields and methods from its superclass, but the constructors of the superclass are not inherited in the subclass. They can only be invoked from constructors of the subclass( es) using the keyword super.

The keyword super refers to superclass of the class in which super appears. The syntax used to call superclass constructor is

super([arguments])

Here, the arguments enclosed in square brackets are optional. The statement super () invokes the constructor with no parameters of its superclass and the statement

super (arguments)

invokes the superclass constructor that matches the arguments. The superclass constructor call must be the first statement in the body of subclass constructor. If one does not specify super, the compiler implicitly inserts super () ; at the beginning of the subclass's default constructor to call the superclass's default constructor.

When you create an instance of the subclass, it invokes the constructors of all the superclasses along the inheritance chain. A superclass constructor is always called before the superclass constructor.

Now let us consider a program to explain the use of super keyword.

class Point  //superclass

{
      private int x,y,z;
      Point(int xl,int yl,int zl)
      {
          System.out.println("Super class constructor is invoked");
          x = xl;
          y = yl;
          z = zl;
      }
      public int getX() {return x;}
      public int getY() {return y;}
      public int getZ() {return z;}
   
}
   class Sphere extends Point //Subclass
{
     private int radius;
     Sphere(int xl,int yl,int zl,int r)
     {
        super(xl,yl,zl); //call point(int xl,int yl,int zl);
        System.out.println("Derived class constructor is invoked");
        radius = r ;
     }
     public int getRadius() {return radius; }
     public double volume()
     {
        return (4*Math.PI*Math.pow(radius,3));
     }
}
   public class SuperKeyword 
{
         public static void main(String[] args)
      {
             Sphere s = new Sphere(2,3,4,5); //create Sphere object
             System.out.println("x coordinate = " +s.getX());
             System.out.println("y coordinate = " +s.getY());
             System.out.println("z coordinate = " +s.getZ());
             System.out.println("Volume of Sphere is = " +s.volume());
     }
}

Super Keyword in Java Example