Reputation: 77
class Clidder {
private final void flipper() {
System.out.println("Clidder");
}
}
public class Clidlet extends Clidder {
public final void flipper() {
System.out.println("Clidlet");
}
public static void main(String args[]) {
new Clidlet().flipper();
}
}
what is the result? to this question I expected the answer "compilation fails" because final method cannot be overridden and it does not allow inheritance. but the answer was "Cliddet" why is that? did I misunderstand something in this concept. how can this be the output? please explain.
Upvotes: 5
Views: 254
Reputation: 1233
In this case private
keyword prevents subclass from accessing the method. As a result Clidlet
asks Clidder
about the method properties, receives response "I keep it private" and executes it's own method.
This case illustrate that the fact that private
precedes (has higher priority than) final
, that private final
== private
and demonstrates the confusion it can lead to.
Upvotes: 0
Reputation: 1955
The answer should be "Cliddet" as your final method has private
access modifier which makes it invisible for the child class. The flipper method in the Clidlet
class effectively hiding the same method in the parent class. This is quite dangerous as a result will depend on whether it is invoked from the superclass or the subclass.
Clidlet clidlet = new Clidlet();
clidlet.flipper(); // prints Clidlet
Clidder clidder = new Clidlet();
clidder.flipper(); // prints Clidder
Upvotes: 0
Reputation: 310885
private
methods are not overridden, so there is no override here, so no violation of final
. In fact final
on a private
method is meaningless, or redundant, take your pick.
Upvotes: 1
Reputation: 835
The private modifier indicates that the method of flipper() in class of Clidder can not be seen from child class Clidlet. So it is not overriding but just looks like a new method declaration in the child class. Private method/field can not be override because it can not be seen.
Upvotes: 4