解釋Java中物件的縮窄。
Java提供各種資料型別來儲存各種資料值。它提供7種基本資料型別(儲存單個值),即boolean、byte、char、short、int、long、float、double,以及引用資料型別(陣列和物件)。
型別轉換/型別轉換 - 將一種基本資料型別轉換為另一種稱為Java中的型別轉換(型別轉換)。您可以透過兩種方式轉換基本資料型別,即擴充套件和縮窄。
縮窄 - 將較高資料型別轉換為較低資料型別稱為縮窄。在這種情況下,轉換不會自動進行,您需要使用強制轉換運算子“( )”顯式轉換。因此,它被稱為顯式型別轉換。在這種情況下,兩種資料型別不必彼此相容。
![]()
示例
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}輸出
Enter an integer value: 67 Character value of the given integer: C
物件的縮窄
您可以將一個(類)型別的引用(物件)轉換為另一個型別。但是,這兩個類之一應該繼承另一個類。
因此,如果一個類繼承了另一個類的屬性,則將超類物件轉換為子類型別被認為是關於物件的縮窄。
但與擴充套件不同,在縮窄的情況下,您需要使用強制轉換運算子。
示例
在下面的Java示例中,我們有兩個類,即Person和Student。Person類有兩個例項變數name和age,以及一個例項方法displayPerson(),它顯示姓名和年齡。
Student擴充套件了Person類,除了繼承的name和age之外,它還有兩個變數branch和student_id。它有一個方法displayData(),它顯示所有四個值。
在main方法中,我們分別建立了這兩個類的物件,並且我們正在嘗試將子類物件轉換為超類型別。
class Person{
private String name;
private 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 Student extends Person {
public String branch;
public int Student_id;
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: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Branch: "+this.branch);
System.out.println("Student ID: "+this.Student_id);
}
public static void main(String[] args) {
//Creating an object of the Student class
Student student = new Student("Krishna", 20, "IT", 1256);
//Converting the object of Student to Person
Person person = new Person("Krishna", 20);
//Converting the object of person to student
student = (Student) person;
student.displayPerson();
student.displayStudent();
}
}執行時錯誤
對於此引用,兩個類的成員都可用,程式成功編譯。但是,當您嘗試執行它時,將引發異常,如下所示:
Exception in thread "main" java.lang.ClassCastException: ther.Person cannot be cast to ther.Student at ther.Student.main(Student.java:41)
要解決此問題,首先需要使用子類物件建立超類引用,然後使用強制轉換運算子將此(超)引用型別轉換為子類型別。
示例
public static void main(String[] args) {
//Converting the object of Student to Person
Person person = new Student("Krishna", 20, "IT", 1256);
//Converting the object of person to student
Student student = (Student) person;
student.displayPerson();
student.displayStudent();
}輸出
Data of the Person class: Name: Krishna Age: 20 Data of the Student class: Name: Krishna Age: 20 Branch: IT Student ID: 1256
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP