5

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

4

4 回答 4

16

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.

于 2010-06-22T11:57:35.277 回答
7

B extends A and therefore B can be cast as A. However the reverse is not true. An instance of A cannot be cast as B.

If you are coming from the Javascript world you may be expecting this to work, but Java does not have "duck typing".

于 2010-06-22T12:00:12.687 回答
1

首先这样做:

  A aClass = new B(); 

现在进行显式转换,它将起作用:

   B b = (B) aClass;

这意味着显式转换必须需要隐式转换。elsewise 不允许显式转换。

于 2015-02-18T00:58:43.620 回答
0

一旦创建了子类的对象,就不能将其类型转换为超类。看看下面的例子

假设: Dog 是继承自 Animal(SuperClass) 的子类

正常类型转换:

Dog dog = new Dog();
Animal animal = (Animal) dog;  //works

错误的类型转换:

Animal animal = new Animal();
Dog dog = (Dog) animal;  //Doesn't work throws class cast exception

下面的 Typecast 确实有效:

Dog dog = new Dog();
Animal animal = (Animal) dog;
dog = (Dog) animal;   //This works

编译器在运行时检查它的语法 内容已实际验证

于 2015-04-10T12:58:57.317 回答