抛出的Java抽象类 [英] Java abstract classes which throw
问题描述
如果我有一个具有以下功能的抽象类 -
If I have an abstract class with the following function -
abstract class A{
void foo(String s) throws Exception{
throw new Exception("exception!");
}
}
然后是另一个扩展抽象类并实现自己版本的 foo 的类 -
And then another class that extends the abstract class and implements its own version of foo -
class B extends A{
void foo(String s){
//do stuff that does *not* throw an exception
}
}
这会产生问题吗?具体在以下测试用例中 -
Will this create problems? Specifically in the following test case -
Collection<A> col = new Collection<A>();
B b = new B();
col.add(b);
for(A a : col){
a.foo();
}
我做了一些测试,似乎没有任何问题,但我不明白为什么 B 的 foo 被调用而不是 A 的
I did some testing and nothing seems to have broken, but I don't understand why B's foo was called and not A's
推荐答案
因为Polymorphism
.
由于在运行时 Collection
中实际对象的类型是 B
,所以 B.foo()
被调用.
Since, at runtime the actual object's type in the Collection
is B
so, B.foo()
was called.
基本上,如果您将子类型对象分配给超类引用,运行时多态性确保子类型的一个实例方法被调用,即如果它被覆盖当然.如果不是,则调用回退到超类版本.
Basically, if you have a sub-type object assigned to a super-class reference the runtime polymorphism makes sure that the sub-type's version of an instance method gets called i.e. if it has been overridden of course. If not, the call falls back upon the super-class version.
重写的方法必须具有
- 相同的方法签名
- 协变返回类型(可以返回子类型)
- 不得抛出更广泛的检查异常 (适用于您的问题和@Dgrin91 的评论,即仅仅因为被覆盖的方法承担了一些风险(抛出异常)不会't 意味着覆盖方法应该做同样的事情;所以,它可能根本不会抛出任何异常)
- 不得使用限制较少的访问修饰符(可以将保护设为公开但不设为私有)
这篇关于抛出的Java抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!