Definition of Super keyword:

It is a keyword using which we can point the immediate super object of the current object. The Super keyword cannot be used in the static blocks. This is because super keyword points to the immediate superclass object of the current object and we know that static blocks will not work in objects.

 

Example:

The following program illustrates that use of a super keyword.

Class first

{

Int I,j;

Void function A()

{

System. Out. Prinln(“ inside the function A() of First class”);

}

}

Class second extends first

{

Int   I, k;

Void function A ()

{

System. Out. Prinln(“ inside the function A() of  second  class”);

Super. Function A (); \\ fun A () of first class is called.

}

Void function1 ()

{

Function A (); // function A () of class second is called.

Super. Function A (); // function A () of class second is called.

Super. i= 10;

}

Public static void main (string args [ ])

{

Second s = new second;

S. functions 1();

Super. Function A (); \\ error.

}

}

 

Uses of keyword super:

  • We can refer to the properties of the immediate superclass object from the subclass object.
  • We can explicitly call immediate super class constructors from the subclass constructors.

Whenever a class extends anther class, always the superclass constructors are executed first.

 

Example:

Class M

{

Int I,j;

M( )

{

System. Out. Prinln(“ inside the M() of class M”);

}

Class N extends M

{

Int I,j;

N ();

{

System. Out. Prinln(“ inside the N() of class N”);

}

Public static void main (string args [ ])

{

N n1 = new N ();

}

}

In every constructor, we have default statement. The default statement is nothing but super ().  As soon as the control entries the constructor of a class whether that class is extending any other class or not. If the statement yes, it creates an object of the super class by executing super (); statement in the current constructor. This is the reason why superclass constructors are executed first.

 

Super Keyword Homework Help