Super Keyword in Java

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.

Example: 

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.

Example:

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.

Example:

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

 

Share this website !!!
Facebook Twitter Linkedin

1. Online Compilers - Compile & Run your C/C++ programs:

✅ Online Compilers

2. Ask your questions or clarify your/others doubts from,

✅ Online Discussion Forums by Fresh2Refresh.com





Close
We Support JALLIKATTU !!!
We Support JALLIKATTU!
By Fresh2Refresh.com
Show Your Support as well. Thanks!