解釋 Java 中物件擴充套件。


Java 提供各種資料型別來儲存各種資料值。它提供了 7 種基本資料型別(儲存單個值),即 boolean、byte、char、short、int、long、float、double,以及引用資料型別(陣列和物件)。

型別轉換/型別轉換 - 將一種基本資料型別轉換為另一種稱為 Java 中的型別轉換(型別轉換)。您可以透過兩種方式轉換基本資料型別,即擴充套件和縮減。

擴充套件 - 將較低資料型別轉換為較高資料型別稱為擴充套件。在這種情況下,轉換是自動完成的,因此稱為隱式型別轉換。在這種情況下,兩種資料型別都應相互相容。

示例

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

物件擴充套件

您可以將一個(類)型別的引用(物件)轉換為另一個。但是,兩個類之一應繼承另一個。

因此,如果一個類繼承了另一個類的屬性,則子類物件到超類型別的轉換被認為是關於物件的擴充套件。

示例

在以下 Java 示例中,我們有兩個類,即 Person 和 Student。Person 類有兩個例項變數 name 和 age,以及一個例項方法 displayPerson(),它顯示 name 和 age。

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 student to person
      person = (Student) student;
      person.displayPerson();
   }
}

輸出

Data of the Person class:
Name: Krishna
Age: 20

簡而言之,超類引用變數可以儲存子類物件。但是,使用此引用,您只能訪問超類成員,如果您嘗試訪問子類成員,則會生成編譯時錯誤。

public static void main(String[] args) {
   Person person = new Student("Krishna", 20, "IT", 1256);
   person.displayStudent();
}

輸出

Student.java:33: error: cannot find symbol
   person.dispalyStudent();
          ^
   symbol: method dispalyStudent()
   location: variable person of type Person
1 error

更新於: 2019-07-30

3K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.