Clone

LJM·2022년 12월 22일
0

Java

목록 보기
12/33

Clone 하려면
클래스에서 Cloneable 구현해야함

Clone 함수 오버라디이딩 해야함

테스트해봤는데 주소가 다르다
값도 변경해봐도 하나만 변경된다
깊은 복사 인듯

class Student implements Cloneable{

    String name;

    Student(String name)
    {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

    @Override
    public String toString() {
        return name;
    }
}
public class CloneTest {
    public static void main(String[] args) throws CloneNotSupportedException {

        Student std1 = new Student("Kim");
        Student std2;
        std2 = (Student) std1.clone();
        std1.setName("Lee");

        System.out.println(std1);
        System.out.println(std2);
    }
}
profile
게임개발자 백엔드개발자

0개의 댓글