多态问题总结

来源:互联网 发布:yy淘宝兼职是真的吗 编辑:程序博客网 时间:2024/06/05 04:15

class Person{
String name = "person";
public void shout(){
System.out.println(name);
}
}
class Student extends Person{
String name = "student";/* 与父类同名的子类的成员属性不能父类的引用变量来访问
得到的还是父类的成员属性,其不够成覆盖*/
String school = "school";
}
class Test {
public static void main(String[] args){
Person p = new Student();
System.out.println(p instanceof Student);//ture
System.out.println(p instanceof Person);//ture
System.out.println(p instanceof Object);//ture
//System.out.println(p instanceof System);//不可转换的类型
System.out.println(p.name);//输出person
//System.out.println(p.school);//error 通过父类的引用变量无法调用子类特有属性与方法
Student s = (Student)p;//向下强制转换,将父类所指向的真实子类类型还原到s
System.out.println(s.name);
System.out.println(s.school);

}
}

输出结果:
true
true
true
person
student
school
0 0
原创粉丝点击