In this article we will see 'What is super keyword in Java', and how to use it with example.

In Java, super keyword is used to refer to immediate parent class of a child class. In other words super keyword is used by a subclass whenever it need to refer to its immediate super class.

Case 1: subclass calling parent class variable

'super' keyword can be used by subclass to refer variables 'super.name' of superclass as shown below:
class A {
	String name = "A";
}

class B extends A {
	String name = "B";

	public void printName() {
		// super used to refer variable of superclass
		System.out.println(super.name + ": " + name);

	}
}

public class Main {
	public static void main(String args[]) {
		B b = new B();
		b.printName(); // prints A: B

	}
}


Case 2: subclass calling parent class method

'super' keyword can be used by subclass to refer methods of superclass 'super.name()' as shown below:
class A {
	public String name(){
		return "A";
	} 
}

class B extends A {
	public String name(){
		return "B";
	} 

	public void printName() {
		System.out.println(super.name() + ": " + name());

	}
}

public class Main {
	public static void main(String args[]) {
		B b = new B();
		b.printName(); // prints A: B

	}
}


Case 3: subclass calling immediate parent class constructor

'super' keyword can be used by subclass to refer constructor of superclass 'super()', in this case super() should be the very first statement of subclass constructor; as shown below:
class A {
	A() {
		System.out.println("From A's constructor");
	}
}

class B extends A {
	B() {
		super();
		System.out.println("From B's constructor");
	}
}

public class Main {
	public static void main(String args[]) {
		B b = new B();

	}
}
Output: Output will be something like this:

From A's constructor
From B's constructor


Both super() and this() must be the very first statement inside a constructor. Hence we cannot use them together.

In this article we have seen 'What is super keyword in Java', and how to use it with example. In upcoming articles we will see more about Java.
  • By Techburps.com
  • Nov 7, 2017
  • Core Java