您如何在Java中上调和下调同一对象?
在Java中将一种数据类型转换为另一种数据类型称为转换。
向上转换-如果将较高的数据类型转换为较低的数据类型,则称为缩小(将较高的数据类型值分配给较低的数据类型变量)。
示例
import java.util.Scanner; public class NarrowingExample { public static void main(String args[]){ char ch = (char) 67; System.out.println("Character value of the given integer: "+ch); } }
输出结果
Character value of the given integer: 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(); //only super class methods //下铸件 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