java中的覆盖方法具有以下功能:java中的覆盖方法约束
1> Overrinding方法应该具有与Parent类方法相同的参数列表。
2>返回类型应该与父类方法的返回类型相同/子类。
3>访问级别应与父类方法相同或更少限制。
4>重写方法可以抛出相同或更窄的异常,而不是更广泛的。
* 只是想知道为什么会这样的点*
* 2 - 为什么子为什么不超? *
3 - 为什么访问级别应该限制较少?
4 - 为什么它应该抛出狭窄的异常?
按我的理解它只是如果我创建一个父类refrence创建一个子类对象,并试图跑下来每个场景,然后
让我们假设A是父类和B是子类均具有方法printAndReturnSomething()
public class A{
public B printAndReturnSomething(){
S.O.P("Inside A Print");
return new B();
}
}
现在我们有孩子的B类为
public class B extends A{
public A printAndReturnSomething(){ // I know this isn't possible to return A but had it been then
S.O.P("Inside A Print");
return new A();
}
}
现在,如果我做这样的事情
A a =new B();
,现在我有一个这样的引用我期待的返回类型为B型的
B returnedValue=a.printAndReturnSomething(); // But it actually calls the child class method and hence returns A. So here comes the contradiction.
Similaraly为情景3和4.我的理解是否正确?我错过了其他更相关的东西吗?
感谢您的回答,特别是最后一行“始终将继承看作”像超类一样行事“,或者”可以像超类一样对待“,所有这些都应该清楚。 – Deva