首页 文章资讯内容详情

在Java中将子类对象分配给超类对象时会发生什么?

2026-06-04 1 花语

在Java中将一种数据类型转换为另一种数据类型称为转换。

如果将较高的数据类型转换为较低的数据类型,则称为窄化(将较高的数据类型值分配给较低的数据类型变量)。

char ch = (char)5;

如果将较低的数据类型转换为较高的数据类型,则称为加宽(将较低的数据类型值分配给较高的数据类型变量)。

Int i = c;

同样,您也可以将一种类型的对象强制转换/转换为其他类型。但是这两个类应该处于继承关系中。然后,

如果将超类转换为子类类型,则在引用方面将其称为窄化(子类引用变量包含超类的对象)。

Sub sub = (Sub)new Super();

如果将Sub类转换为Super类类型,则在引用方面被称为加宽(拥有Sub类对象的Super类引用变量)。

Super sup = new Sub();

将子类对象分配给超类变量

因此,如果将子类的一个对象赋给超类的引用变量,那么子类对象就被转换为超类的类型,这个过程称为加宽(就引用而言)。

但是,使用此引用,只有在尝试访问子类成员时,才可以访问超类的成员,否则将生成编译时错误。

例子

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

Student扩展了人员类,除了继承的名称和年龄,它还有两个变量branch和student_id。它有一个方法displaydata()显示所有四个值。

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

class Person{ public String name; public int age; public Person(String name, int age){ this.name = name; this.age = age; } public void displayPerson() { System.out.println("Data of the Person class: "); 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("Data of the Student class: "); System.out.println("Name: "+super.name); System.out.println("Age: "+super.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);

使用此引用,您只能访问超类的方法,即显示person()。相反,如果您尝试访问子类方法(即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