Use of super Keyword in Java

In this class, We discuss Use of super Keyword in Java.

The reader should have prior knowledge of inheritance. Click Here.

Super Keyword:

The below are the uses of super keyword.

1) To call super class variables.

2) To call super class methods.

3) To call super class constructors.

We take examples and understand all the three concepts.

The below diagram shows the code for calling super class variables.

In the above code method “m2” is using p value.

c = p + p;

We have p variable in both classes A and B.

The above line will look p value in class B.

The value of p is 50. so 50 + 50 =100.

Suppose, we need to use the p value from class A. We use super keyword.

c = super.p + p.

The super.p is the value from class A. ie 30.

The second p is the value from class B. ie 50.

Super is a keyword used to find the variables from the first occurrence of super classes.

The below example shows the multi-level inheritance.

super.p is checking in class B. but p variable not present in class B.

Check p variable in class A. So get p value from class A.

The first occurrence of p value in our super classes will be obtained.

Example on Methods:

The below diagram shows an example to call super class methods.

In the above code all the classes having m1 method.

If we need to use the m1 method from super class we write super.m1().

Example on constructors:

The below code shows the example to call super class constructor.

In the above code we have a class weight.

The class “weight” constructor is calling super class constructor using super().

Note: The first line in the constructor should be super.