x

Java – Super Keyword

PREV     NEXT

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


Accessing parent class variable using JAVA 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.

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.


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.

Output:

Display of B

Display of A

Calling parent class constructor using super keyword:

Super() invokes parent class constructor.

Example:

Output:

A’s constructor

B’s constructor

PREV     NEXT



Like it? Please Spread the word!