Let’s learn super keyword in java.
super keyword in java
super is a keyword it is used to refer super class instance members. To understand super keyword clearly first learn polymorphism and inheritance.
Let’s see example on super keyword.
// parent class class Demo { int a = 6; } // child class class Example extends Demo { int a = 15; void display(int a) { System.out.println(super.a); } public static void main(String[] args) { Example obj = new Example(); obj.display(24); } }
Output:
6
Use of super keyword in java
1.) super keyword is used to refer immediate parent class instance variable
class Car { String color = "white"; } class Audi extends Car { String color = "green"; void print(String color) { // prints color of Audi class System.out.println(color); // prints color of Car class System.out.println(super.color); } public static void main(String[] args) { Audi obj = new Audi(); obj.print("blue"); } }
Output:
blue
white
2.) super keyword is used to invoke immediate parent class method – In the below example super keyword is used to invoke immediate parent class method. Invoking immediate parent class method should be used only if method is overridden.
class Car { void acclerate() { System.out.println("car accelerating…."); } } class Audi extends Car { void acclerate() { System.out.println("audi accelerating…."); } void display() { accelerate(); super.accelerate(); } public static void main(String[] args) { Audi obj = new Audi(); obj.display(); } }
Output:
audi accelerating….
car accelerating….
In the above example Car class and Audi class have accelerate() method. When display() method is called it will call accelerate() method of Audi class by default. To call Car class accelerate() method use super keyword.
3.) super keyword is used to invoke immediate parent class constructor –
class Car { Car() { System.out.println("Car constructor"); } } class Audi extends Car { Audi() { super(); System.out.println("Audi constructor"); } public static void main(String[] args) { Audi obj = new Audi(); } }
Output:
Car constructor
Audi constructor
NOTE: super and this keyword cannot be used in static area. Let’s see an example,
class Parent { String str = "Parent"; } class Child extends Parent { String str = "Child"; public static void display() { System.out.println(this.str); System.out.println(super.str); } } class Demo { public static void main(String[] args) { Child c = new Child(); c.display(); } }
Output:
Immediately we get compile time error saying: java: non-static variable this cannot be referenced from a static context. java: non-static variable super cannot be referenced from a static context