#
"super" keyword in Java
This tutorial explains to you how super
keyword in Java.
#
"super" keyword in Java - theory
Method overriding in Java appears when we declare a method in subclass which is already present in parent class. The main advantage of method overriding in Java is that the class can give its own specific implementation to an inherited method without even modifying the parent class.
Warning
Don't confuse Java method overriding
with Java method overloading
. For more information you can take a look
here.
Info
The super
keyword in Java is used when in a child class (subclass) when you want to:
- run a method from the super class (parent class)
- call the constructor of the superclass from the subclass
#
"super" keyword in Java - example
Here it is an example:
- defining the Shape class:
Shape.java
public class Shape {
public void drawShape(){
System.out.println("Draw shape from Shape Class.");
};
}
- extend the Shape class and use the
super
keyword
Triangle.java
public class Triangle extends Shape {
public void drawShape() {
System.out.println("Draw shape from Triangle Class.");
super.drawShape();
}
}
- define the main application
MainApp.java
public class MainApp {
public static void main(String [] args) {
Triangle triangle = new Triangle();
triangle.drawShape();
}
}
When you run the main class you will see:
Draw shape from Triangle Class.
Draw shape from Shape Class.
Process finished with exit code 0