Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ประโยชน์ของ Object Cloning ใน Java


Object cloning คือการสร้าง สำเนาทุกประการของออบเจ็กต์ (exact copy) ใช้เมธอด clone() ของคลาส Object คลาสต้อง implements Cloneable interface มิฉะนั้น clone() จะโยน CloneNotSupportedException

เมธอด clone() ช่วยประหยัดการประมวลผลสำหรับสร้างสำเนาเป๊ะๆ หากใช้ new keyword จะต้องประมวลผลมาก จึงควรใช้ object cloning

ไวยากรณ์

protected Object clone() throws CloneNotSupportedException

ตัวอย่าง

public class EmployeeTest implements Cloneable {
    int id;
    String name = "";
    Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Employee clone() throws CloneNotSupportedException {
        return (Employee)super.clone();
    }

    public static void main(String[] args) {
        Employee emp = new Employee(115, "Raja");
        System.out.println(emp.name);
        try {
            Employee emp1 = emp.clone();
            System.out.println(emp1.name);
        } catch(CloneNotSupportedException cnse) {
            cnse.printStackTrace();
        }
    }
}

ผลลัพธ์

Raja Raja