如何在Java中将子类变量转换为超类类型?
继承是两个类之间的关系,其中一个类继承另一个类的属性。这种关系可以使用`extends`关键字定义为:
public class A extends B{
}
继承属性的类称为子类或子类,而其属性被继承的类称为超类或父类。
在继承中,超类成员的副本会在子类对象中创建。因此,使用子类对象,您可以访问这两个类的成员。
将子类变量转换为超类类型
您可以直接将子类变量(值)赋值给超类变量。简而言之,超类引用变量可以持有子类对象。但是,使用此引用只能访问超类成员,如果尝试访问子类成员,则会生成编译时错误。
示例
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 Sample extends Person { public String branch; public int Student_id; public Sample(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 Person("Krishna", 20); //Converting super class variable to sub class type Sample sample = new Sample("Krishna", 20, "IT", 1256); person = sample; person.displayPerson(); } }
输出
Data of the Person class: Name: Krishna Age: 20
示例
class Super{ public Super(){ System.out.println("Constructor of the Super class"); } public void superMethod() { System.out.println("Method of the super class "); } } public class Test extends Super { public Test(){ System.out.println("Constructor of the sub class"); } public void subMethod() { System.out.println("Method of the sub class "); } public static void main(String[] args) { Super obj = new Test(); obj.superMethod(); } }
输出
Constructor of the Super class Constructor of the sub class Method of the super class
广告