覆盖 Java 中的私有方法 [英] Overriding private methods in Java
问题描述
正如此处所述,在Java中覆盖私有方法是无效的因为父类的私有方法是自动最终的,并且对派生类隐藏".我的问题主要是学术性的.
As succinctly described here, overriding private methods in Java is invalid because a parent class's private methods are "automatically final, and hidden from the derived class". My question is largely academic.
不允许父类的私有方法被覆盖"(即,在子类中独立实现,具有相同的签名)如何不违反封装?父类的私有方法不能被子类访问或继承,符合封装原则.它是隐藏的.
How is it not a violation of encapsulation to not allow a parent's private method to be "overridden" (ie, implemented independently, with the same signature, in a child class)? A parent's private method cannot be accessed or inherited by a child class, in line with principles of encapsulation. It is hidden.
那么,为什么要限制子类实现自己的具有相同名称/签名的方法?对此是否有良好的理论基础,或者这只是某种务实的解决方案?其他语言(C++ 或 C#)对此有不同的规定吗?
So, why should the child class be restricted from implementing its own method with the same name/signature? Is there a good theoretical foundation for this, or is this just a pragmatic solution of some sort? Do other languages (C++ or C#) have different rules on this?
推荐答案
你不能覆盖一个私有方法,但是你可以在派生类中引入一个没有问题的方法.这编译得很好:
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.
这篇关于覆盖 Java 中的私有方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!