Can I override a private method in Java?

前端 未结 10 1220
天涯浪人
天涯浪人 2020-11-29 08:26

I know I can use reflection to invoke a private method, and to get or set the value of a private variable, but I want to override a method.

public class Supe         


        
10条回答
  •  再見小時候
    2020-11-29 09:22

    You can't override a private method.

    An overriding method can only exist in a subclass of the overridden method. If the method that you want to override is marked private, overriding it is not possible because the subclass doesn't inherit anything marked private, thus severing ties between that private method and anything in the subclass, including any of the subclass's methods.

    To "override" means allowing the JVM to determine which method to use based on the instance type that you are invoking it with. The theory of polymorphism explains what makes this possible. In order for the JVM to be able to say "these methods are connected, one overrides the other", the JVM must be able to view the overridden method from within the subclass that contains the overriding method.

    That being said, the classes in the case you provided will still compile, but neither of the methods will be invoked based on the JVMs independently run instance-based invocation. They will merely be different methods altogether that fail to be recognized by the JVM as overridden or overriding.

    Furthermore, if you are using an IDE such as NetBeans, using the @Override annotation will instruct the compiler that you are overriding the method with the same signature in the superclass. If you don't do this, you will get a warning suggesting that you make the annotation. You will get a compilation error, however, if you apply this annotation when:

    • there is no method with a matching signature in the superclass

    OR

    • the method in the superclass that you are trying to override is marked private or final

    Refer to the official Oracle documentation https://docs.oracle.com/javase/tutorial/java/IandI/override.html for the following excerpt:

    Instance Methods

    ...The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed.... When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.

    Overriding can be very confusing because it involves the JVM taking action seemingly independently. Just remember that without access to the method[s] in the superclass (in other words, for all methods marked private), the subclass can't invoke or override the said method[s] because it can't inherit them to do so.

提交回复
热议问题