Learn what does the super keyword means in java and how to use it.

super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super.

Example 1

Have a look at this example, we'll use super and we'll send parameters through the constructor:

class Animal {
    public Animal(String arg) {
        System.out.println("Constructing an animal: " + arg);
    }
}

class Cat extends Animal {
    public Cat() {
        super("This is from cat constructor");
        System.out.println("Constructing a cat.");
    }
}

public class Test {
    public static void main(String[] a) {
        new Cat();
    }
}

The output will be like:

Constructing an animal: This is from cat constructor 
Constructing a dog.

The cat function is initialized, then the super method is executed and invokes Animal first and finally print "Constructing a cat" line.

Example 2

Now take a look to the following example, we'll use the super keyword to invoke directly a method from the parent class:

class Base
{
    int a = 100;
    void Show()
    {
        System.out.println(a);
    }
}

class Son extends Base
{
    int a = 200;
    void Show()
    {
        // Call Show method from parent class
        super.Show();
        System.out.println(a);
    }
    public static void Main(String[] args)
    {
        new Son().Show();
    }
}

The output will look like:

100
200

We'll execute the Show method from the Son class, and inside the Show method of the son class we'll execute the show method of the Base class using super.Show

Notes

Whenever we are using either super() or super(arguments) in the derived class constructors the super always must be as a first executable statement in the body of derived class constructor otherwise we get a compile time error (Call to super must be the first statement in the constructor).


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors