1. 程式人生 > 實用技巧 >Java中5種建立物件的方式

Java中5種建立物件的方式

眾所周知,在Java中,類提供物件的藍圖,您可以從類建立物件。在Java中有許多不同的方法來建立物件。

以下是一些在Java中建立物件的方法:

1、 使用new關鍵字

使用new關鍵字是建立物件的最基本方法。這是在java中建立物件的最常見方法。幾乎99%的物件都是這樣建立的。通過使用這個方法,我們可以呼叫我們想要呼叫的任何建構函式(無引數或引數化建構函式)。

// Java program to illustrate creation of Object 
// using new keyword 
public class NewKeywordExample 
{ 
    String name 
= "GeeksForGeeks"; public static void main(String[] args) { // Here we are creating Object of // NewKeywordExample using new keyword NewKeywordExample obj = new NewKeywordExample(); System.out.println(obj.name); } }

輸出:

GeeksForGeeks

2、使用New Instance

如果我們知道類的名稱並且如果它有一個公共的預設建構函式,我們就可以通過Class.forName來建立類的物件。forName實際上在Java中載入類,但不建立任何物件。要建立類的物件,必須使用類的newInstance()方法。

// Java program to illustrate creation of Object 
// using new Instance 
public class NewInstanceExample 
{ 
    String name = "GeeksForGeeks"; 
    public static void main(String[] args) 
    { 
        
try { Class cls = Class.forName("NewInstanceExample"); NewInstanceExample obj = (NewInstanceExample) cls.newInstance(); System.out.println(obj.name); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }

輸出:

GeeksForGeeks

3、使用clone()方法

每當對任何物件呼叫clone()方法時,JVM實際上會建立一個新物件,並將前一個物件的所有內容複製到該物件中。使用clone方法建立物件不會呼叫任何建構函式
要使用clone()方法,類要實現Cloneable介面並且實現clone()方法。

// Java program to illustrate creation of Object 
// using clone() method 
public class CloneExample implements Cloneable 
{ 
    @Override
    protected Object clone() throws CloneNotSupportedException 
    { 
        return super.clone(); 
    } 
    String name = "GeeksForGeeks"; 

    public static void main(String[] args) 
    { 
        CloneExample obj1 = new CloneExample(); 
        try
        { 
            CloneExample obj2 = (CloneExample) obj1.clone(); 
            System.out.println(obj2.name); 
        } 
        catch (CloneNotSupportedException e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 

輸出:

GeeksForGeeks

注:

  • 這裡我們建立的是現有物件的克隆,而不是任何新物件。
  • 類需要實現可克隆介面,否則將丟擲CloneNotSupportedException.

4、使用反序列化

每當我們序列化並反序列化一個物件時,JVM會建立一個單獨的物件。在反序列化,JVM不使用任何建構函式來建立物件。
要反序列化物件,我們需要在類中實現可序列化介面。

序列化物件:

// Java program to illustrate Serializing 
// an Object. 
import java.io.*; 

class DeserializationExample implements Serializable 
{ 
    private String name; 
    DeserializationExample(String name) 
    { 
        this.name = name; 
    } 

    public static void main(String[] args) 
    { 
        try
        { 
            DeserializationExample d = 
                    new DeserializationExample("GeeksForGeeks"); 
            FileOutputStream f = new FileOutputStream("file.txt"); 
            ObjectOutputStream oos = new ObjectOutputStream(f); 
            oos.writeObject(d); 
            oos.close(); 
            f.close(); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 

DeserializationExample類的物件使用writeObject()方法進行序列化,然後寫入file.txt檔案。

物件的反序列化:

// Java program to illustrate creation of Object 
// using Deserialization. 
import java.io.*; 

public class DeserializationExample 
{ 
    public static void main(String[] args) 
    { 
        try
        { 
            DeserializationExample d; 
            FileInputStream f = new FileInputStream("file.txt"); 
            ObjectInputStream oos = new ObjectInputStream(f); 
            d = (DeserializationExample)oos.readObject(); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
        System.out.println(d.name); 
    } 
} 

輸出:

GeeksForGeeks

5、使用Constructor類的newInstance()方法:

這類似於類的newInstance()方法。java.lang.reflect.Constructor類中有一個newInstance()方法,可用於建立物件。通過使用此newInstance()方法,它也可以呼叫引數化建構函式和私有建構函式。
// Java program to illustrate creation of Object 
// using newInstance() method of Constructor class 
import java.lang.reflect.*; 

public class ReflectionExample 
{ 
    private String name; 
    ReflectionExample() 
    { 
    } 
    public void setName(String name) 
    { 
        this.name = name; 
    } 
    public static void main(String[] args) 
    { 
        try
        { 
            Constructor<ReflectionExample> constructor 
                = ReflectionExample.class.getDeclaredConstructor(); 
            ReflectionExample r = constructor.newInstance(); 
            r.setName("GeeksForGeeks"); 
            System.out.println(r.name); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
    } 
} 

輸出:

GeeksForGeeks
newInstance