Super Keyword

The super keyword in java is a reference variable which is used to refer immediate parent class object. The keyword is mainly used within a child class when it wants to access

It can be seen that the variable is mainly used to get something from the parent class.

super within constructor of child class

class Vehicle {
	public Vehicle() {
		System.out.println("I am a vehicle.")
	}
	public Vehicle(final String message) {
		System.out.println(message+ "From vehicle");
	}
}
class Car extends Vehicle {
	public Car() {
		super()
		System.out.println("I am a car.");
	}
	public Car(final String message) {
		super(message);
		System.out.println("I am a car.");
	}
}
Car c  = new Car()
//will display
I am a vehicle
I am a car

Car c = new Car("Hello");
//will display
Hello from vehicle
Hello from car

Couple of important things to observe:

super to invoke method of the parent class

This is used when we want to call parent class method. So whenever a parent and child class have same named methods then to resolve ambiguity we use super keyword. This code snippet helps to understand the said usage of super keyword.

class Vehicle {
	public Vehicle() {
	}
	public void message() {
		System.out.println("I am a vehicle.")
	}
}
class Car extends Vehicle {
	public Car() {
	}
	public void message(final String message) {
		super.message()
		System.out.println("I am a car.")
	}
}
new Car().message()
//will display
I am a vehicle
I am a car

super to invoke variable of the parent class

This scenario occurs when a derived class and base class has same data members. In that case there is a possibility of ambiguity for the JVM. Below example can help to understand better.

class Vehicle {
	public String value = "I am a Parent"
	public Vehicle() {
	}
}
class Car extends Vehicle {
public String value = "I am a Child"
	public Car() {
	}
	public void message() {
		System.out.println(super.value)
		System.out.println(value)
	}
}
new Car().message()
//will display
I am a Parent
I am a Child

Recommend Reading

  1. How java manages Memory?
  2. Why is it advised to use hashcode and equals together?
  3. Comparable and Comparator in java
  4. How to create Singleton class in Java?
  5. Difference between equals and ==?
  6. When to use abstract class over interface?
  7. Difference between final, finally and finalize
  8. Why is it recommended to use Immutable objects in Java