super keyword in Java

  • super keyword refers to the immediate base class.
  • super reference variable is used to call a base class constructor.
  • You can use it to access variable or method of the base class.

To access variable of the base class

A super reference variable is used to access base class's variables, when both derived class and base class has variables with the same name.

class Parent
{
	int age = 40;	
}
class Child extends Parent
{
	int age = 10;
	public void printage()
	{
		System.out.println("Parent age = "+super.age);
		System.out.println("Child age = "+age);
	}
	public static void main(String args[])
	{
		Child c = new Child();
		c.printage();
	}
}

Output

Parent age = 40
Child age = 10

In the above example, both Parent and Child class has common property age. If we print age then it will print Child class age field. To access the Parent class's age property, we have used super keyword.

To access methods of the base class

A super keyword is used to call a base class method. When derived class has overridden a base class method, in that situation if you want to call the base class overridden method, then use super keyword.

class Parent
{
	int age = 40;
	public void printage()
	{
		System.out.println("Parent age = "+age);
	}	
}
class Child extends Parent
{
	int age = 10;
	public void printage()
	{		
		System.out.println("Child age = "+age);
	}
	public void show()
	{
		super.printage();
		printage();
	}
	public static void main(String args[])
	{
		Child c = new Child();
		c.show();
	}
}

Output

Parent age = 40
Child age = 10

In the above example, Parent and Child class has printage() method. If we call printage() method in Child class then priority will be given to Child class's printage() method. So, we have used super keyword to call Parent class printage() method.

To access constructor of the base class

The super keyword is used to invoke a base class constructor. If super() is present, then it must be placed at the beginning of the constructor. Otherwise, compiler will add super() automatically.

class Parent
{
	int age = 40;
	public Parent()
	{
		System.out.println("parent is created.");
	}	
}
class Child extends Parent
{
	int age = 10;
	public Child()
	{
		super();
		System.out.println("child is created");
	}
	public static void main(String args[])
	{
		Child c = new Child();		
	}
}

Output

parent is created.
child is created.