如何在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 Sample("Krishna", 20, "IT", 1256);
//Converting super class variable to sub class type
Sample obj = (Sample) person;
obj.displayPerson();
obj.displayStudent();
}
}输出
Data of the Person class: Name: Krishna Age: 20 Data of the Student class: Name: Krishna Age: 20 Branch: IT Student ID: 1256
示例
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 sup = new Test();
//Converting super class variable to sub class type
Test obj = (Test) sup;
obj.superMethod();
obj.subMethod();
}
}输出
Constructor of the super class Constructor of the sub class Method of the super class Method of the sub class
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP