Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
100 views
in Technique[技术] by (71.8m points)

java - Errors In Polymorphism

I am kinda new to java and I have a question about polymorphism and possible errors. Assume that we have this:

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{
}

and Assume that we have something like this:

Animal t1 = new Tiger();
Fish f1 = new Salmon();
Tiger t2= new Tiger();
Salmon s1 = new Salmon();

What is The errors in following lines (Compile Time Error, Runtime Error or No Error):

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();

I've Answered it like bellow but I've thought it's kinda weird that I found no Runtime Error. if all of them is correct can u make an example where we have runtime error (in this polymorphism concept)

My Answer:

a  compile error
b  no error
c  no error
d  compile error
e  compile error
f  no error
g  no error
h  compile error
question from:https://stackoverflow.com/questions/65934509/errors-in-polymorphism

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Focusing on the part about "how to get to an exception at runtime".

You figured yourself that Cat c3 = (Cat) new Salmon(); is wrong. And obviously, the compiler can already tell you that.

Why? Because the compiler can "see" that you create a Salmon, and that you then want to treat that as Cat, which isn't meaningful.

The only thing you need to get "past" the compiler is to "hide" that fact, like:

Salmon s1 = new Salmon();
Animal a3 = (Fish) s1;
Cat c3 = (Cat) a3;

As soon as you introduce a3, you are able to "hide" the fact that s1 is actually a Salmon.

Of course: even in my example, a smarter compiler could understand that a3 must be a Salmon, can't be a Cat. But java plays it "simple and conservative" here. The compiler only recognizes the most basic casting violations, and for good or bad, the java language ignores many situations that could be detected at compile time, too. That makes it easier to implement compilers, the traddeoff is that your code is more exposed to such exceptions at runtime.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...