Super Keyword in Java

Super refer to parent class. It holds the reference id of
parent section of child class object. Observe below example.

class A
{
                int
x=10;
}
class B extends A
{
                int
x=20;

}
Super Keyword in Java
Here you can see that in child object, two separate sections
are created namely parent section and child section. So super actually refer to
parent section.

Use of Super Keyword in Java

There are three usage of super keyword in java.
  • Access parent class instance variable.
  • Invoke parent class method.

Below program will show all the three usage of super
keyword.

           
Super Keyword in Java - Output

  • Here both the classes have variable x and method show(). To access variable of child class we simply write x and to access variable of parent class we write super.x.
  • Similarly, to invoke method of child we simple write
    show() and to invoke method of
    parent we write super.show(). In this way super is also used to remove the problem
    of method overriding.
  • super() must be first line of the constructor. In above
    example we have written super() in first line of child class constructor to
    call parent class constructor.
  • Super can’t be used in static method.
  • By default super is first line of constructor. Super keyword
    and this keyword can’t be used together in constructor.

Leave a Comment

Your email address will not be published. Required fields are marked *