覆盖Java中的私有方法 [英] Overriding private methods in Java

查看:113
本文介绍了覆盖Java中的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简洁地描述了此处,覆盖Java中的私有方法无效因为父类的私有方法是自动最终的,并且从派生类中隐藏。我的问题主要是学术性的。



如何违反封装,不允许父母的私有方法被覆盖(即,在子类中独立实施,具有相同的签名)?根据封装原则,子类无法访问或继承父级的私有方法。它是隐藏的。



那么,为什么要限制子类使用相同的名称/签名实现自己的方法?有没有一个很好的理论基础,或者这只是某种实用的解决方案?其他语言(C ++或C#)对此有不同的规则吗?

解决方案

你不能覆盖一个私有方法,但您可以在派生类中引入一个没有问题。编译正常:

  class Base 
{
private void foo()
{
}
}

class Child延伸基数
{
private void foo()
{
}
}

请注意,如果您尝试应用 @Override 注释到 Child.foo()您将收到编译时错误。只要您的编译器/ IDE设置为在缺少 @Override 注释时为您提供警告或错误,一切都应该很好。不可否认,我更喜欢覆盖的C#方法作为关键字,但在Java中显然为时已晚。



对于C#处理覆盖私有方法 - 私有方法首先不能是虚方法,但你当然可以在基类中引入一个与私有方法同名的新私有方法。 / p>

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.

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()
    {
    }
}

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.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆