Java – Super Keyword

PREV     NEXT

‘super’ keyword is used to refer the members of immediate parent class.

Accessing parent class variable using super keyword:

In the below example, class B is a subclass of class A. The display() method of class B prints the value of x. Both class A and class B have the variable x.The compiler by default, takes the value of current class instance variable. But when the parent class instance variable is to be accessed, then the super keyword is used.

COMPILE & RUN

Output:

Value of x:20

In the below example the display method of class B prints the value of parent class instance variable x. Here ‘super.x’ refers to the parent class instance variable.


COMPILE & RUN

Output:

Value of x:10

Accessing parent class method using super keyword:

In the below example, class B is a subclass of class A. Both class A and class B have the method message().The compiler by default, calls the message() method in the current class. But when the parent class method is to be called, then the super keyword is used. Here ‘super.message()’ calls the message() method of parent class.

COMPILE & RUN

Output:

Display of B

Display of A

Calling parent class constructor using super keyword:

Super() invokes parent class constructor.


Example:

COMPILE & RUN

Output:

A’s constructor

B’s constructor

PREV     NEXT

Share this website !!!
Facebook Twitter Linkedin