Using super to Call Superclass Constructors


There are two common forms of super. The first calls the superclass builder. The second is used to access a member of the superclass that was hidden by a member of the subclass.

Super's First Use

A subclass can call a constructor assigned by its superclass using the following super form:

super(arg-list);

Here, the arg-list specifies any argument required by the constructor in the superclass. Super () must always be the first statement effective inside the subclass constructor.

Program
class X
{
 int _a,_b;
 X(int a,int b)
 {
  this._a=a;
  this._b=b;
 }
}
class Y extends X
{
 int _c;
 Y(int a, int b, int c)
 {
  // base class constructor are called
  super(a,b);
  _c=c;
 }
 void SumOfabc()
 {
  int sum=_a+_b+_c;
  System.out.println("Sum of _a + _b + _c : "+sum);
 }
}
public class Main 
{
  public static void main(String[] args) 
  {
    Y obj=new Y(10,20,30);
    obj.SumOfabc();
  }
}

In the example above, the subclass constructor is called the superclass constructor. When a subclass object is created, the values in the superclass data are initialized from the values sent to its constructor.


A Second Use for super

The second form of super works somewhat like this, it always refers to the superclass of the subclass is used. The following are common forms of this use:

super.member

Members here can be variable in either method or example.

This second form of super is most applicable in situations where the name of the subclass member hides the members of the same name in the superclass. Consider this general classification:

Program
// Using super to overcome name hiding.
class X
{
 int a;
}
// Create a subclass by extending class X.
class Y extends X
{
 int a; // this a hides the a in X.
 Y(int i, int j)
 {
  super.a=i; // a in X
  a=j; // a in Y
 }
 void show()
 {
  System.out.println("a in superclass : "+super.a);
  System.out.println("a in subclass : "+a);
 }
}
public class Main 
{
  public static void main(String[] args) 
  {
    Y obj=new Y(10,20);
    obj.show();
  }
}

Although the instance variable "a" in "Y" hides the "a" in "X", super allows access to the "a" defined in the superclass. As you will see, super can also be used to call methods that are hidden by a subclass.