Exact way to use final methods in java

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 result? To this question, I expected the answer “compilation will fail”, because the final method cannot be overridden, and it does not allow inheritance. but the answer was "Cliddet," why? I misunderstood something in this concept. How can this be the result? Explain, please.

+5
source share
4 answers

A private modifier indicates that the flipper () method in the Clidder class cannot be seen from the Clidlet child class. Thus, this does not override, but simply looks like a new method declaration in a child class. A private method / field cannot be overridden because it cannot be seen.

+4
source

private methods are not overridden, so there is no override here, so final not violated. In fact, final with the private method is senseless or redundant, take your choice.

+1
source

The answer should be "Cliddet", since your final method has a private access modifier that makes it invisible to the child class. The flipper method in the Clidlet class effectively hides the same method in the parent class. This is quite dangerous, as the result will depend on whether it is called from a superclass or a subclass.

 Clidlet clidlet = new Clidlet(); clidlet.flipper(); // prints Clidlet Clidder clidder = new Clidlet(); clidder.flipper(); // prints Clidder 
0
source

In this case, the private keyword prevents the subclass from accessing the method. As a result, Clidlet asks Clidder about the properties of the method, receives the response "I keep it private" and executes its own method.

This case illustrates that the fact that private precedes (has a higher priority than) final is private final == private and demonstrates the confusion it could lead to.

0
source

All Articles