为什么我们不能用私有扩展类方法覆盖基类方法? [英] Why can’t we override a base class method with private extended class method?
问题描述
class One {
void foo() { }
}
class Two extends One {
private void foo() { /* more code here */ }
}
为什么上面的代码片段是错误的?
Why is the above snippet of code wrong?
推荐答案
我将尝试结合其他答案中的思想来提出一个答案.
首先,让我们看一下代码中正在发生的事情.
First off, let's take a look at what's going on in the code.
查看代码
One
类具有程序包专用的foo
方法:
The One
class has a package-private foo
method:
class One {
// The lack of an access modifier means the method is package-private.
void foo() { }
}
Two
类是One
类的子类,并且foo
方法被覆盖,但是具有访问修饰符private
.
The Two
class which subclasses the One
class, and the foo
method is overriden, but has the access modifier private
.
class Two extends One {
// The "private" modifier is added in this class.
private void foo() { /* more code here */ }
}
问题
Java语言不允许子类降低子类中方法,字段或类的可见性,因此,降低foo
方法可见性的Two
类是不合法的.
The Java language does not allow subclasses to reduce the visibility of a method, field or class in a subclass, therefore, the Two
class reducing the visibility of the foo
method is not legal.
为什么降低能见度是一个问题?
考虑我们要使用One
类的情况:
Consider the case where we want to use the One
class:
class AnotherClass {
public void someMethod() {
One obj = new One();
obj.foo(); // This is perfectly valid.
}
}
在这里,在One
实例上调用foo
方法是有效的. (假设AnotherClass
类与One
类位于同一程序包中.)
Here, calling the foo
method on the One
instance is valid. (Assuming that the AnotherClass
class is in the same package as the One
class.)
现在,如果要实例化Two
对象并将其放置在类型为One
的obj
变量中怎么办?
Now, what if we were to instantiate the Two
object and place it in the obj
variable of the type One
?
class AnotherClass {
public void someMethod() {
One obj = new Two();
obj.foo(); // Wait a second, here...
}
}
Two.foo
方法是私有的,但是One.foo
方法将允许访问该方法.我们这里有问题.
The Two.foo
method is private, yet, the One.foo
method would allow the access to the method. We've got a problem here.
因此,在考虑继承时允许降低可见性没有多大意义.
Therefore, it doesn't make much sense to allow reduction of visibility when taking inheritance into account.
链接
- 控制对类成员的访问-关于Java教程中的访问修饰符.
- Controlling Access to Members of a Class - Explanations of access modifiers from The Java Tutorials.
这篇关于为什么我们不能用私有扩展类方法覆盖基类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!