Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.
Can We Override Static Methods in Java?
Let’s try the following Java program to find out the answer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classBase{
publicstaticvoidfoo(){
System.out.println("Base foo");
}
}
classDerivedextendsBase{
publicstaticvoidfoo(){
System.out.println("Derived foo");
}
}
publicclassMain{
publicstaticvoidmain(String[] args){
Base obj = new Derived();
obj.foo();
}
}
Output:
1
Base foo
From the output, we know that the method according to the type of reference, instead of the one according to the object being referred, is called, which means it’s decided at compile time, instead of run time. So we can conclude that we can’t override static methods in Java.
Can We Override Final Methods in Java?
We can use final specifier to indicate that a method can’t be overridden by subclasses. Definitely the answer to the question is NO. Let’s try the following Java program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classBase{
publicfinalvoidfoo(){
System.out.println("Base foo");
}
}
classDerivedextendsBase{
publicfinalvoidfoo(){
System.out.println("Derived foo");
}
}
publicclassMain{
publicstaticvoidmain(String[] args){
Base obj = new Derived();
obj.foo();
}
}
Compiler Error:
1
2
3
4
5
Main.java:8: error: foo() in Derived cannot override foo() in Base
public final void foo() {
^
overridden method is final
1 error
Can We Override Private Methods in Java?
According to Bruce Eckel’s Thinking in Java, private methods are implicitly final, which means the answer is still NO. Let’s try the following Java program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classBase{
privatevoidfoo(){
System.out.println("Base foo");
}
}
classDerivedextendsBase{
privatevoidfoo(){
System.out.println("Derived foo");
}
}
publicclassMain{
publicstaticvoidmain(String[] args){
Base obj = new Derived();
obj.foo();
}
}
Compiler Error:
1
2
3
4
Main.java:16: error: foo() has private access in Base