class Person{
public void say(){
System.out.println("Person");
}
}class Student extends Person{
@Override
public void say(){
System.out.println("Student");
}
}
public class Pet { public static void main(String[] args) {

Person p = new Person();
if(p instanceof Person){
((Student)p).say();
}
}}
请问为什么会抛出ClassCastException

解决方案 »

  1.   

    因为p是Person类型的,你强制转换为Student类型的当然会出错啦!
      

  2.   

    if(p instanceof Student){
    ((Student)p).say();
    }
      

  3.   

    Person p = new Person();
    if(p instanceof Person){
    ((Student)p).say();
    }
    }
    ==》Person p = new Student();
    if(p instanceof Student){
    ((Student)p).say();
    }
    }
      

  4.   

    Student继承Person类,不可以将Person类的实例转化为Student类。
      

  5.   

    这其实就是继承的问题,一般可以用“has a”与“is a”来表示。即父类 “has a”子类,子类 “is a”父类。通俗点说,学生是人,但不能说人(都)是学生。故会抛出classCastException。