为什么我们不能在子类中分配较弱的权限 [英] why can't we assign weaker privilege in subclass

查看:88
本文介绍了为什么我们不能在子类中分配较弱的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,它有一个方法,默认情况下访问说明符是public。现在,我想在子类中扩展此类,并且我想覆盖此方法以使访问说明符为private。编译此代码时,我收到编译错误:

I have a class which has a method whose access specifier by default is public. Now, I would like to extend this class in a subclass and I want to override this method to have access specifier "private". When compiling this code, I am getting a compilation error:


尝试分配较弱的访问权限。

"attempting to assign weaker access privileges".

有人可以向我解释在子类中分配较弱的权限有什么问题吗?

Could somebody please explain to me what is wrong with assigning weaker privileges in a subclass?

这是导致编译错误的代码:

Here is the code that caused the compilation error:

class Superclass 
{
    void foo() 
    {
        System.out.println("Superclass.foo");
    }
}

class Subclass extends Superclass 
{
    private void foo() 
    {
        System.out.println("Subclass.foo");
    }
}


推荐答案

简短的回答是,它是不允许的,因为它会破坏类型的可替代性;另请参阅 Liskov替代原则(LSP)

The short answer is that it is not allowed because it would break type substitutability; see also the Liskov Substititution Principle (LSP).

重点是Java(和其他编程语言)中的多态性依赖于您能够处理子类的实例,就像它是超类的实例一样。但是如果该方法在子类中受到限制,您会发现编译器无法确定访问规则是否允许调用方法...

The point is that polymorphism in Java (and other programming languages) relies on you being able to treat an instance of a subclass as if it was an instance of the superclass. But if the method is restricted in the subclass, you find that the compiler cannot figure out whether the access rules allow a method to be called ...

例如,let假设您的示例代码是合法的:

For instance, lets assume that your example code was legal:

// Assume this code is in some other class ...

SuperClass s1 = new SuperClass();

s1.foo();                          // OK!

SuperClass s2 = new Subclass();

s2.foo();                          // What happens now?

SuperClass s3 = OtherClass.someMethod();

s3.foo();                          // What happens now?

如果你决定是否 s2.foo() s2 类型允许使用c $ c>,然后允许从外部调用 private 方法子类的抽象边界。

If you base the decision on whether s2.foo() is allowed on the declared type of s2, then you allow a call to a private method from outside the abstraction boundary of Subclass.

如果您根据 s2 所引用的对象的实际类型做出决定,则无法进行访问静态检查。 s3 案例使这一点更加清晰。编译器绝对无法知道 someMethod 返回的对象的实际类型是什么。

If you base the decision on the actual type of the object that s2 refers to, you cannot do the access check statically. The s3 case makes this even clearer. The compiler has absolutely no way of knowing what the actual type of the object returned by someMethod will be.

访问可能导致运行时异常的检查将成为Java应用程序中的主要错误来源。这里讨论的语言限制避免了这个令人讨厌的问题。

Access checks that could result in runtime exceptions would be a major source of bugs in Java application. The language restriction under discussion here avoids this nasty problem.

这篇关于为什么我们不能在子类中分配较弱的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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