package java类型转换和向上向下转型;
class People
{
public void say(){
System.out.println("I am a person");
}
}
class Student extends People
{
public void say(){
System.out.println("I am a student");
}
}
public class Demo {
public static void main(String[] args) {
People peo=new People();
peo.say();
System.out.println("peo对象的Class是:" +peo.getClass());
People stu_peo=new Student();
stu_peo.say();
System.out.println("stu_peo对象的Class是:" +stu_peo.getClass());
//有语法错误,虽然在编译时没有错误,但是在运行时会提示:People cannot be cast to Student
//Student peo_stu1=(Student)peo;
//peo_stu1.say();
Student peo_stu2=(Student)stu_peo;
peo_stu2.say();
System.out.println("peo_stu2对象的Class是:" +peo_stu2.getClass());
}
}
//输出结果:
I am a person
peo对象的Class是:class java类型转换和向上向下转型.People
I am a student
stu_peo对象的Class是:class java类型转换和向上向下转型.Student
I am a student
peo_stu2对象的Class是:class java类型转换和向上向下转型.Student
|
|