Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - ClassCastException

i have two classes in java as:

class A {

 int a=10;

 public void sayhello() {
 System.out.println("class A");
 }
}

class B extends A {

 int a=20;

 public void sayhello() {
 System.out.println("class B");
 }

}

public class HelloWorld {
    public static void main(String[] args) throws IOException {

 B b = (B) new A();
     System.out.println(b.a);
    }
}

at compile time it does not give error, but at runtime it displays an error : Exception in thread "main" java.lang.ClassCastException: A cannot be cast to B

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This happens because the compile-time expression type of new A() is A - which could be a reference to an instance of B, so the cast is allowed.

At execution time, however, the reference is just to an instance of A - so it fails the cast. An instance of just A isn't an instance of B. The cast only works if the reference really does refer to an instance of B or a subclass.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...