Java 中建立物件的不同方法?


在 Java 中,類是一種使用者定義的資料型別/藍圖,我們在其中宣告方法和變數。

public class Sample{
}

宣告類後,需要建立(例項化)一個物件。您可以使用多種方法建立物件 -

使用 new 關鍵字

通常,使用 new 關鍵字建立物件,如下所示 -

Sample obj = new Sample();

示例

在下面的 Java 程式碼中,我們有一個名為 sample 的類,它有一個方法(display)。從 main 方法中,我們正在例項化 Sample 類並呼叫 display() 方法。

 線上演示

public class Sample{
   public void display() {
      System.out.println("This is the display method of the Sample class");
   }
   public static void main(String[] args){
      //Instantiating the Sample class
      Sample obj = new Sample();
      obj.display();
   }
}

輸出

This is the display method of the Sample class

使用 newInstance() 方法

名為 Class 的類的 newInstance() 方法建立由此 Class 物件表示的類的物件。

您可以透過將類的名稱作為字串傳遞給 forName() 方法來獲取類的 Class 物件。

Sample obj2 = (Sample) Class.forName("Sample").newInstance();

示例

在下面的 Java 程式碼中,我們有一個名為 sample 的類,它有一個方法(display)。從 main 方法中,我們正在使用 Class 類的 newInstance() 方法建立 Sample 類的物件。

 線上演示

public class Sample{
   public void display() {
      System.out.println("This is the display method of the Sample class");
   }
   public static void main(String[] args) throws Exception{
      //Creating the Class object of Sample class
      Class cls = Class.forName("Sample");
      Sample obj = (Sample) cls.newInstance();
      obj.display();
   }
}

輸出

This is the display method of the Sample class

使用 clone() 方法

Object 類的 clone() 建立並返回當前類的物件。

示例

在下面的 Java 程式碼中,我們有一個名為 sample 的類,它有一個方法(display)。從 main 方法中,我們正在建立 Sample 類的物件,並從中使用 clone() 方法建立另一個物件。

public class Sample{
   public void display() {
      System.out.println("This is the display method of the Sample class");
   }
   public static void main(String[] args) throws Exception{
      //Creating the Class object of Sample class
      Sample obj1 = new Sample();
      //Creating another object using the clone() method
      Sample obj2 = (Sample) obj1.clone();
      obj2.display();
   }
}

輸出

This is the display method of the Sample class

使用 lang.reflect 中的建構函式類

java.lang.reflect.Constructor 類的 newInstance() 方法使用當前建構函式建立並返回一個新物件。

示例

在下面的 Java 程式碼中,我們有一個名為 sample 的類,它有一個方法(display)。從 main 方法中,我們正在使用 java.lang.reflect.Constructor 類建立 Sample 類的物件。

 線上演示

import java.lang.reflect.Constructor;
public class Sample {
   public void display() {
      System.out.println("This is the display method of the Sample class");
   }
   public static void main(String[] args) throws Exception{
      //Creating a Constructor class
      Constructor constructor = Sample.class.getDeclaredConstructor();
      //Creating an object using the newInstance() method
      Sample obj = constructor.newInstance();
      obj.display();
   }
}

輸出

This is the display method of the Sample class

更新於: 2020-06-29

801 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告