java中超类引用变量可以保存子类的对象吗

是的,超类引用变量实际上可以容纳子类对象,如果是对象,它会变宽(将较低的数据类型转换为较高的数据类型)。

但是,使用此引用,您只能访问超类的成员,如果尝试访问子类的成员,则会生成编译时错误。

示例


在下面的Java示例中,我们有两个类,分别是Person和Student。 Person类具有两个实例变量名称和年龄,以及一个实例方法displayPerson(),该方法显示名称和年龄。

Student继承了person类,除了继承的名字和年龄之外,它还有两个变量branch和student_id,它有一个displayData()方法,它显示所有四个值。

在main方法中,我们为子类对象分配了超类引用变量

class Person{
   private String name;
   private int age;
   public Person(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void displayPerson() {
      System.out.println("Person类的数据: ");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
   }
}
public class Student extends Person {
   public String branch;
   public int Student_id;
   public Student(String name, int age, String branch, int Student_id){
      super(name, age);
      this.branch = branch;
      this.Student_id = Student_id;
   }
   public void displayStudent() {
      System.out.println("Student类的数据: ");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Branch: "+this.branch);
      System.out.println("Student ID: "+this.Student_id);
   }
   public static void main(String[] args) {
      Person person = new Student("Krishna", 20, "IT", 1256);
      person.displayPerson();
   }
}

输出结果

Data of the Person class:
Name: Krishna
Age: 20

访问子类方法

当您将子类对象分配给超类引用变量时,如果尝试访问子类的成员,则使用该引用会生成编译时错误。

示例

在这种情况下,如果您将Student对象分配给Person类的引用变量为-

Person person = new Student("Krishna", 20, "IT", 1256);

使用此引用,您只能访问超类的方法,即displayPerson()。相反,如果您尝试访问子类方法(即displayStudent()),则会生成编译时错误。

因此,如果用以下命令替换之前程序的主方法,则会产生编译时错误。

public static void main(String[] args) {
   Person person = new Student("Krishna", 20, "IT", 1256);
   person.displayStudent();
}

编译时错误

Student.java:33: error: cannot find symbol
   person.dispalyStudent();
        ^
   symbol: method dispalyStudent()
   location: variable person of type Person
1 error