为什么我们不能用私有扩展类方法覆盖基类方法? [英] why cant 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.
查看代码
一个
类有一个包私有 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() { }
}
两个
类,它继承一个
类,而 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
方法的可见性是不合法的。
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.
为什么降低可见性成为问题?
考虑我们要使用的情况
class:
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.
}
}
这里,调用 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.)
现在,如果我们要实例化两个
对象并将其放在 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屋!