Java 'super' Keyword Tutorial
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Usage of Java 'super' Keyword
-
1. To refer immediate parent class instance variable
We can use
superkeyword to access the data member or field of parent class. It is used if parent class and child class have same fields. -
2. To invoke immediate parent class method
The
superkeyword call can be used to invoke parent class method. It should be used if subclass contains the same method as parent class.class Animal { void eat() { System.out.println("eating..."); } } class Dog extends Animal { void eat() { System.out.println("eating bread..."); } void bark() { System.out.println("barking..."); } void work() { super.eat(); bark(); } } -
3. To invoke immediate parent class constructor
The
super()call can be used to invoke the parent class constructor.
Note: `super()` must be the first statement in constructor.class Bird { private String name; public Bird(String name) { this.name = name; } } class Parrot extends Bird { public Parrot(String name) { super(name); } }