为什么派生类重写方法不应该比java中的基类更具限制性? [英] Why derived class overriding method should not be more restrictive than base class in java?
问题描述
为什么派生类重写方法不应该比java中的基类更具限制性。为什么编译器会抛出错误?你能解释一下原因吗?
Why derived class overriding method should not be more restrictive than base class in java.Why compiler throws error?can you please anyone explain reason for that?
推荐答案
关键是只知道你的超类的调用者应该仍然可以使用它给出的子类的任何实例。考虑这种情况:
The point is that a caller who only knows about your superclass should still be able to use any instance of the subclass that it's given. Consider this situation:
public class Super
{
public void print()
{
System.out.println("Hello!");
}
}
public class Sub extends Super
{
@Override
void print() // Invalid
{
System.out.println("Package access");
}
}
现在从另一个包中,想象我们有:
Now from a different package, imagine we had:
public void printSuper(Super x)
{
x.print();
}
我们用以下方式调用:
printSuper(new Sub());
您期望做什么?你覆盖了这个方法,所以它应该打印包访问 - 但这意味着你要从另一个包调用一个包访问方法...
What would you expect that to do? You're overriding the method, so it should print "package access" - but then that means you're calling a package access method from a different package...
基本上,这只是 Liskov替代原则的一个例子。您应该能够将子类的任何实例视为超类的实例,并且很难看出它如何适应在子类中使事情更具限制性。
Basically, this is just one example of the Liskov Substitution Principle in action. You should be able to treat any instance of a subclass as an instance of the superclass, and it's hard to see how that fits in with making things more restrictive in a subclass.
这篇关于为什么派生类重写方法不应该比java中的基类更具限制性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!