Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override "private" method in java

Tags:

There something ambiguous about this idea and I need some clarifications.

My problem is when using this code:

public class B {      private void don() {         System.out.println("hoho private");     }     public static void main(String[] args) {         B t = new A();         t.don();     } }  class A extends B {     public void don() {         System.out.println("hoho public");     } } 

The output is hoho private.

Is this because the main function is in the same class as the method don, or because of overriding?

I have read this idea in a book, and when I put the main function in another class I get a compiler error.

like image 234
basel man Avatar asked Jan 22 '16 03:01

basel man


People also ask

Can we override private and protected methods in Java?

Yes, the protected method of a superclass can be overridden by a subclass. If the superclass method is protected, the subclass overridden method can have protected or public (but not default or private) which means the subclass overridden method can not have a weaker access specifier.

Can you override private method using inner class?

No, you cannot override private methods in Java, private methods are non-virtual in Java and access differently than non-private one.


2 Answers

You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the @Override annotation when you intend to override,

class A extends B {     @Override     public void don() { // <-- will not compile if don is private in B.         System.out.println("hoho public");     } } 

In this case why didn't compiler provide an error for using t.don() which is private?

The Java Tutorials: Predefined Annotation Types says (in part)

While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

like image 72
Elliott Frisch Avatar answered Sep 23 '22 23:09

Elliott Frisch


is this because the main function is in the same class as the method "don"

No, it's because A's don() is unrelated to B's don() method, in spite of having the same name and argument list. private methods are hidden inside their class. They cannot be invoked directly by outside callers, such as main method in your case, because they are encapsulated inside the class. They do not participate in method overrides.

like image 36
Sergey Kalinichenko Avatar answered Sep 26 '22 23:09

Sergey Kalinichenko