且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

覆盖 Java 中的私有方法

更新时间:2021-08-29 21:29:16

你不能覆盖一个私有方法,但是你可以在派生类中引入一个没有问题的方法.这编译得很好:

You can't override a private method, but you can introduce one in a derived class without a problem. This compiles fine:

class Base
{
   private void foo()
   {
   }
}

class Child extends Base
{
    private void foo()
    {
    }
}

请注意,如果您尝试将 @Override 注释应用于 Child.foo(),您将收到编译时错误.只要您将编译器/IDE 设置为在缺少@Override 注释时向您发出警告或错误,一切都应该没问题.诚然,我更喜欢将 override 作为关键字的 C# 方法,但在 Java 中这样做显然为时已晚.

Note that if you try to apply the @Override annotation to Child.foo() you'll get a compile-time error. So long as you have your compiler/IDE set to give you warnings or errors if you're missing an @Override annotation, all should be well. Admittedly I prefer the C# approach of override being a keyword, but it was obviously too late to do that in Java.

至于C#对覆盖"私有方法的处理——私有方法一开始就不能是虚拟的,但是你当然可以在基类中引入一个与私有方法同名的新私有方法.

As for C#'s handling of "overriding" a private method - a private method can't be virtual in the first place, but you can certainly introduce a new private method with the same name as a private method in the base class.