Các cách khởi tạo đối tượng trong Java (Java Constructor)

Các cách khởi tạo đối tượng trong Java (Java Constructor).

Giả sử mình có class Customer như sau:

package stackjava.com.constructor.demo;

public class Customer {
  
  private String name;
  private String address;

  // getter - setter
}

Bây giờ mình sẽ trình bày các cách để tạo mới một đối tượng Customer

Cách 1: Dùng từ khóa new

Ví dụ:

Customer c1 = new Customer();

Cách 2: Dùng method newInstance()

Customer c2 = (Customer)Class.forName("stackjava.com.constructor.demo.Customer").newInstance();

Customer c3 = (Customer) Customer.class.getClassLoader().loadClass("stackjava.com.constructor.demo.Customer").newInstance();

Customer c4 = Customer.class.newInstance();

Constructor<Customer> constructor = Customer.class.getConstructor();
Customer c5 = constructor.newInstance();

Cách 3: Clone object

Với cách này thì Class của đối tượng được clone phải implement interface Cloneable và override lại method clone():

package stackjava.com.constructor.demo;

public class Customer implements Cloneable {
  
  private String name;
  private String address;

  // getter - setter

  @Override
  public Object clone() throws CloneNotSupportedException {
    return super.clone();
  }

}

Ví dụ:

Customer c1 = new Customer();
Customer c2 = (Customer) c1.clone();

Cách 4: Sử dụng deserialization

Cách này chính là chuyển một mảng byte thành đối tượng.

(Xem lại: Java Serializable là gì? Serialization và Deserialization trong Java)

Ví dụ:

Customer c1 = new Customer();

// Serialization
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("customer.dat"));
out.writeObject(c1);
out.close();

// Deserialization
ObjectInputStream in = new ObjectInputStream(new FileInputStream("customer.dat"));
Customer c2 = (Customer) in.readObject();

Lưu ý:

Với cách 1 và cách 2 thì chương trình sẽ gọi tới hàm khởi tạo của class Customer do đó class Customer phải có hàm khởi tạo public hoặc access modifier tương ứng để có thể truy cập vào hàm khởi tạo.

Với cách 3 và cách 4 thì chương trình không gọi tới hàm khởi tạo của class Customer.

 

Okay, Done!

Download code ví dụ trên tại đây.

 

Reference:

https://dzone.com/articles/5-different-ways-to-create-objects-in-java-with-ex

https://stackoverflow.com/…-different-ways-to-create-an-object-in-java

stackjava.com