If your method overrides one of its superclass’s methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:
public class Superclass { public void printMethod() { System.out.println("Printed in Superclass."); } }
Here is a subclass, called Subclass, that overrides printMethod():
public class Subclass extends Superclass { // overrides printMethod in Superclass public void printMethod() { super.printMethod(); System.out.println("Printed in Subclass"); } public static void main(String[] args) { Subclass s = new Subclass(); s.printMethod(); } }
Within Subclass, the simple name printMethod() refers to the one declared in Subclass, which overrides the one in Superclass. So, to refer to printMethod() inherited from Superclass, Subclass must use a qualified name, using super as shown. Compiling and executing Subclass prints the following:
super is used to invoke parent class constructor
The super keyword can also be used to invoke the parent class constructor as given below:
class Vehicle{ Vehicle(){ System.out.println("Vehicle is created"); } } class Bike extends Vehicle{ Bike(){ super();//will invoke parent class constructor System.out.println("Bike is created"); } public static void main(String args[]){ Bike b=new Bike(); } }
Note:super() is added in each class constructor automatically by compiler.
As we know well that default constructor is provided by compiler automatically but it also adds super() for the first statement.If you are creating your own constructor and you don’t have either this() or super() as the first statement, compiler will provide super() as the first statement of the constructor.
Another example of super keyword where super() is provided by the compiler implicitly.
class Vehicle{ Vehicle(){ System.out.println("Vehicle is created"); } } class Bike extends Vehicle{ int speed; Bike(int speed){ this.speed=speed; System.out.println(speed); } public static void main(String args[]){ Bike b=new Bike(10); } }
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…