Method Overriding in Java
Method Overriding
If a subclass has the same method defined in the superclass, it is called method overriding.
Rules
- Method must have the same name at superclass and subclass.
- We can’t override the method, which is static and final.
Example
class Mic{
void printInfo(){
System.out.println("Welcome to Default Mic Info");
}
}
class Boya extends Mic{
void printInfo(){
System.out.println("Welcome to Boya Mic Info");
}
}
public class Main {
public static void main(String[] args) {
Mic m1 = new Mic();
Boya b1 = new Boya();
m1.printInfo();
b1.printInfo();
}
}
In this example, we have defined the printInfo method in the subclass as defined as superclass, but it has a different implementation.
The super
Keyword
We can access the superclass method from the subclass by using the super
keyword.
Example
class Mic{
void printInfo(){
System.out.println("Welcome to Default Mic Info");
}
}
class Boya extends Mic{
void printInfo(){
super.printInfo();
System.out.println("Welcome to Boya Mic Info");
}
}
public class Main {
public static void main(String[] args) {
Mic m1 = new Mic();
Boya b1 = new Boya();
m1.printInfo();
b1.printInfo();
}
}