如何在 Java 中对同一对象进行向上和向下转换?

java 8object oriented programmingprogramming更新于 2025/4/15 7:07:17

在 Java 中将一种数据类型转换为其他数据类型称为强制转换。

向上转换 − 如果将较高的数据类型转换为较低的数据类型,则称为缩小(将较高的数据类型值分配给较低的数据类型变量)。

示例

import java.util.Scanner;
public class NarrowingExample {
   public static void main(String args[]){
      char ch = (char) 67;
      System.out.println("给定整数的字符值:"+ch);
   }
}

输出

给定整数的字符值:C

向下转换 − 如果将较低的数据类型转换为较高的数据类型,则称为扩展(将较低的数据类型值分配给较高的数据类型变量)。

示例

public class WideningExample {
   public static void main(String args[]){
      char ch = 'C';
      int i = ch;
      System.out.println(i);
   }
}

输出

Integer value of the given character: 67

向上和向下转换同一个对象

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

  • 如果您将超类转换为子类类型,则在引用方面称为缩小(子类引用变量保存超类的对象)。

Sub sub = (Sub)new Super();
  • 如果您将子类转换为超类类型,则在引用方面称为扩大(超类引用变量保存子类的对象)。

Super sup = new Sub();

示例

以下 Java 程序演示了如何对同一对象进行向上和向下转换。

class Person{
   public String name;
   public int age;
   Person(){}
   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;
   Student(){}
   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 Person();
      Student student = new Student("Krishna", 20, "IT", 1256);
      //向上转换
      person = student;
      person.displayPerson(); //仅限超类方法
      //向下转换
      student = (Student) person;
      student.displayPerson();
      student.displayStudent();
   }
}

输出

Data of the Person class:
Name: Krishna
Age: 20
Data of the Person class:
Name: Krishna
Age: 20
Data of the Student class:
Name: Krishna
Age: 20
Branch: IT
Student ID: 1256

相关文章