JAVA父类引用指向子类的对象是什么意思?

如题所述

父类 Person 子类 Student
可以这样定义 Person p = new Student();
就是你问的 “JAVA父类引用指向子类的对象”
但是你得注意:父类的引用指向子类的话,此时的 p 只能使用Person类中存在的方法,但是子类
Student类中扩充的方法就不能调用了
class Person {
private int age ;
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setAge(int age){
this.age = age;
}
publc int getAge(){
return age ;
}
}

class Student extends Person {
private Strng school ;
public void setSchool(String school){
this.school = school;
}
public String getSchool(){
return this.school;
}
}
public class Demo{
public static void main(String [] args){
Person p = new Student();
//p.setSchool("清华大学")
//String school = p.getSchool(); //以上的两个语句都是错误的,你自己看看吧
}
}
温馨提示:答案为网友推荐,仅供参考
相似回答