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
452 views
in Technique[技术] by (71.8m points)

java - ClassCastException vs. "cannot cast" compilation error

Studying for my OCA Java SE 7 Programmer I exam, so newbie question. I have an example question I do not understand. The following code compiles, but gives a ClassCastException at runtime:

interface Roamable {
}

class Phone {
}

public class Tablet extends Phone implements Roamable {
    public static void main(String... args) {
        Roamable var = (Roamable) new Phone();
    }
}

When I change Roamable var = (Roamable) new Phone(); into Roamable var = (Roamable) new String(); I get a compilation error right away.

Two questions:

  1. Why does the code above compile at all? Phone seems unrelated to Roamable to me?
  2. Why does the code compile with new Phone(), but doesn't it compile with new String()?
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Why does the code above compile at all? Phone seems unrelated to Roamable to me?

yes because Roamable is an interface it might cause a Run-time exception but not compile time exception, because even if Phone doesn't implement Roamable, a subclass of Phone might, hence the compiler has no way to know it but at the Run time.

It is already defined in java language specification. Check out my answer here.

Why does the code compile with new Phone(), but doesn't it compile with new String()?

Because class String is declared as public final class in java.lang package. As specified in jls 8.1.1.2 final class section: a class declared as final can't be extended and hence it won't have any subclass. So, the compiler already knows that String can't be extended: hence no subclass's existence is possible to implement interface Roamable

Edit: (With response to your below comment)

Let us assume that B is a subclass of A which implements an interface T.

Now an statement :

   T t = (T)new A();

is essentially same as:

   A aObj = new A() ;
   T t = (T)aObj ; // a run-time exception happen

before running into conclusion, let us do the same thing with an object of B:

   A aObj = new B();
   T t = (T)aObj; // no exception happen.

so, the real reason with super class and sub class here is the reference. The aObj class in this second code example is also an instance of class A but it is also an instance of class B which has implemented T.


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

...