为什么以下代码给出了一个classcast异常?

Abh*_*h28 0 java inheritance

给出下面的代码:

//Super class 
class A {
    void m1() {
        System.out.println("A");
    }
}

//Extending the super class  
class B extends A {
    void m1() {
        System.out.println("B");
    }
}

// Class with the main method
public class C extends B {
    void m1() {
        System.out.println("C");
    }
}

//in some main method
B b1 = new B(); //creating B object
System.out.println(b1 instanceof A); //gives true
B b = (B) new A();
b.m1();
Run Code Online (Sandbox Code Playgroud)
  1. instanceof运营商提供了真正所以B是类的一个对象A.
  2. 但是,为什么在投放AB其给人ClassCastException即使B是子类型的A

Kon*_*kov 7

new A();根本不是B.

这跟你说"每只动物都是猫,没有例外"一样.哪个不是真的.

然而,在浇铸BA会是正确的(因为每一个猫是动物,没有例外):

A a = (A) new B();
Run Code Online (Sandbox Code Playgroud)