给出下面的代码:
//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)
instanceof运营商提供了真正所以B是类的一个对象A.A到B其给人ClassCastException即使B是子类型的A?new A();根本不是B.
这跟你说"每只动物都是猫,没有例外"一样.哪个不是真的.
然而,在浇铸B到A会是正确的(因为每一个猫是动物,没有例外):
A a = (A) new B();
Run Code Online (Sandbox Code Playgroud)