What is difference between super and super() in Java?

What is difference between super and super() in Java?


super and super() look alike, but they are very different in their functionality (purpose).
  1. super with variables and methods: super is used to call super class variables and methods by the subclass object when they are overridden by subclass.
  2. super() with constructors: super() is used to call super class constructor from subclass constructor.

Let us discuss them programmatically.

A) super keyword with variables

In the following program, super class Test has x variable and subclass has also x variable. That is, x variable of super class is overridden by subclass. If subclass object calls x, it calls its own. In the code it is shown how the subclass calls super class x. The magic keyword is super keyword.


super and super()
Output screenshot on super and super()

System.out.println("Subclass x value: " + x);
System.out.println("Super class x value: " + super.x);

x will call subclass x and super.x will call super class x.

Now let us see how to use super keyword with methods.

B) super keyword with methods

In the following code, display() method exist with both super class Test and subclass Demo. Naturally, subclass object will call its own display() method. It is shown how the subclass object calls super class display() method.


super and super()
Output screen on super and super()

super.display();

In the above statement, super.display() will call, super class display() method.

Note: super cannot be used from static context. That is, super cannot be used from static methods including main().

C) super() with constructors

In the following code, the super class Test has constructors overloaded – one default and one with int parameter.


super and super()
Output screen on super and super()

Demo d1 = new Demo();

The object creation d1 calls Demo class default constructor.

The statement super(50) in the subclass default constructor, calls super class matching constructor, that is, the constructor with int parameter.

Leave a Reply

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