日期:2014-05-20  浏览次数:20859 次

类型信息的问题
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


------解决方案--------------------
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 Student();
if (p instanceof Person) {
((Student) p).say();
}
}

}
------解决方案--------------------
Person p = new Person();
if(p instanceof Person){
((Student)p).say();
}
==>

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


------解决方案--------------------
因为是声明的变量是子类型,你强转成父类型,编译可以通过,但是实际运行的时候不行,像楼上两位这么改即可。