【发布时间】:2021-05-02 04:40:04
【问题描述】:
我对 java 有点陌生,我有一个关于多态性和可能的错误的问题。 假设我们有这个:
public interface Animal {
}
public abstract class Cat implements Animal{
}
public abstract class Fish implements Animal {
}
public class Salmon extends Fish{
}
public class Tiger extends Cat{
}
并假设我们有这样的事情:
Animal t1 = new Tiger();
Fish f1 = new Salmon();
Tiger t2= new Tiger();
Salmon s1 = new Salmon();
以下几行中的错误是什么(编译时错误、运行时错误或无错误):
Cat c1 = new Cat();
Cat c2 = (Tiger) t1;
Animal a1 = s1;
Animal a2 = new Animal();
Fish f1 = (Fish) t2;
Animal a3 = (Fish) s1;
Animal a4 = (Cat) new Tiger();
Cat c3 = (Cat) new Salmon();
我已经像下面这样回答了它,但我觉得我发现没有运行时错误有点奇怪。如果所有这些都是正确的,你可以举一个我们有运行时错误的例子(在这个多态概念中)
我的回答:
a compile error
b no error
c no error
d compile error
e compile error
f no error
g no error
h compile error
【问题讨论】:
-
好吧,您只需运行该代码即可测试您的答案。你不需要任何其他人。
-
我运行代码,这就是我得到的答案。我对如何发生运行时错误感到困惑?
标签: java error-handling polymorphism runtime-error