如何在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);
//Up casting
person = student;
person.displayPerson(); //only super class methods
//Down casting
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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP