如何在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("Person类的数据: ");
      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("学生班数据: ");
      System.out.println("Name: "+super.name);
      System.out.println("Age: "+super.age);
      System.out.println("Branch: "+this.branch);
      System.out.println("学生卡: "+this.Student_id);
   }
   public static void main(String[] args) {        
      Person person = new Sample("Krishna", 20, "IT", 1256);      
      //将超类变量转换为子类类型
      Sample obj = (Sample) person;      
      obj.displayPerson();
      obj.displayStudent();
   }
}
输出结果
Person类的数据:
Name: Krishna
Age: 20
学生班数据:
Name: Krishna
Age: 20
Branch: IT
学生卡: 1256

示例

class Super{
   public Super(){
      System.out.println("Constructor of the super class");
   }
   public void superMethod() {
      System.out.println("超类的方法 ");
   }
}
public class Test extends Super {
   public Test(){
      System.out.println("Constructor of the sub class");
   }
   public void subMethod() {
      System.out.println("子类的方法 ");
   }
   public static void main(String[] args) {        
      Super sup = new Test();      
      //将超类变量转换为子类类型
      Test obj = (Test) sup;      
      obj.superMethod();
      obj.subMethod();
   }
}
输出结果
Constructor of the super class
Constructor of the sub class
超类的方法
子类的方法