Super Keyword in Java | Java Inheritance | Super In Java | Java For Beginner .



Super Keyword

Super has two general forms:-
  1. The first calls the superclass’ constructor.
  2. The second is used to access a member of the superclass that has been hidden by a member of a subclass.
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super.

Using super to Call Superclass Constructors

A subclass can call a constructor defined by its superclass by use of the following form of super:

super(arg-list);

Here, arg-list specifies any arguments needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass’ constructor.

To see how super( ) is used, See below Example..

// BoxWeight now uses super to initialize its Box attributes.

class BoxWeight extends Box
{
   double weight; // weight of box

   // initialize width, height, and depth using super()
   BoxWeight(double w, double h, double d, double m)
   {
      super(w, h, d); // call superclass constructor
      weight = m;
   }
}


Here, BoxWeight( ) calls super( ) with the arguments w, h, and d. This causes the Box( )
constructor to be called, which initializes width, height, and depth using these values.

BoxWeight no longer initializes these values itself.

A Second Use for super to access instance variable and methods.

The second form of super acts somewhat like this, except that it always refers to the superclass
of the subclass in which it is used. 

This usage has the following general form:

super.member

Here, member can be either a method or an instance variable.

Example:-

class A
{
   int i;
}

// Create a subclass by extending class A.
class B extends A
{
   int i; // this i hides the i in A
   B(int a, int b)
   {
      super.i = a; // i in A
      i = b; // i in B
   }
   void show()
   {
      System.out.println("i in superclass: " + super.i);
      System.out.println("i in subclass: " + i);
   }
}
class UseSuper
{
   public static void main(String args[])
      {
         B subOb = new B(1, 2);
         subOb.show();
      }
}


Output:-

i in superclass: 1
i in subclass: 2


Post a Comment

1 Comments