Java抽象类抛出 [英] Java abstract classes which throw

查看:143
本文介绍了Java抽象类抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个具有以下功能的抽象类 -

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

推荐答案

因为多态性

由于在运行时, Collection 中的实际对象的类型是 B so, B.foo()被调用。

Since, at runtime the actual object's type in the Collection is B so, B.foo() was called.

基本上,如果你有一个子-type 对象分配给超类引用运行时多态性确保子类型的 实例方法 / strong>被称为ie,如果它已被 覆盖 当然。

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的评论,即只是因为被覆盖的方法有一些风险(抛出异常)并不意味着重写方法应该这样做;所以它根本不会抛出任何异常)

  • 不得使用限制较少的访问修饰符(可以保护公众而不是私人)

  • the same method signature
  • a covariant return type (a sub-type can be returned)
  • must not throw broader checked exceptions (applies to your question and @Dgrin91's comment i.e. just because the overridden method took some risks (threw exceptions) doesn't mean that the overriding method should do the same; so, it may not throw any exceptions at all)
  • must not use a less restrictive access modifier (can make protected to public but not private)

这篇关于Java抽象类抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆