[Java] Object 클래스 - clone()

이지현·2023년 1월 13일
0

Java

목록 보기
14/46
post-thumbnail

✔️ Object 클래스의 메서드

메서드설명
public boolean equals(Object obj)객체 자신과 객체 obj가 같은 객체인지 여부 반환
public int hashCode()객체 자신의 해시코드 반환
public String toString()객체 자신의 정보를 문자열로 반환
protected Object clone()객체 자신의 복사본 반환
public Class getClass()객체 자신의 클래스 정보를 담고 있는 Class 인스턴스 반환
public void notify()객체 자신을 사용하려고 기다리는 쓰레드를 하나만 깨움
public void notifyAll()객체 자신을 사용하려고 기다리는 모든 쓰레드를 깨움
publid void wait(), public void wait(long timeout), public void wait(long timeout, int nanos)다른 쓰레드가 notify()나 notifyAll()을 호출할 때까지 현재 쓰레드를 무한히 또는 지정된 시간(timeout, nanos)동안 기다리게 함
protected void finalize()객체가 소멸될 때 가비지 컬렉터에 의해 자동적으로 호출, 이 때 수행되어야하는 코드가 있을 때 오버라이딩(거의 사용안함)

✔️ clone()

1. 정의 : 자신을 복제하여 새로운 인스턴스 생성

💡 clone()을 사용하기 위해서는 복제할 클래스가 Cloneable 인터페이스를 구현해야 함

  • Object 클래스의 clone 메소드 접근제어자가 protected이기 때문에 class Student에서 clone 메소드를 호출할 수 없음
  • class Student에서 clone 메소드를 오버라이딩 해 접근제어자를 public으로 바꿔줌

2. 예시

class Student implements Cloneable {
	int grade;
    String name;
    
    @Override
    public Object clone() {
    	Object obj = null;
        try {
        	obj = super.clone();
        } catch(CloneNotSupportedException e) {
        }
        return obj;
    }
}

public class CloneEx {
    public static void main(String[] args) {
        Student st = new Student(3, 홍길동);
        Student stCopy = (Student)st.clone();
        System.out.println(st);
        System.out.println(stCopy);
    }
}

✔️ 공변 변환 타입(covariant return type)

1. 정의 : 공변 반환타입을 이용해서 오버라이딩할 때 조상 메소드의 반환타입을 자손 클래스 타입으로 변경할 수 있음

2. 예시

class Student implements Cloneable {
	int grade;
    String name;
    
    @Override
    public Student clone() { // 반환타입을 Object -> Student로 변경
    	Object obj = null;
        try {
        	obj = super.clone();
        } catch(CloneNotSupportedException e) { // Student로 타입으로 형변환
        }
        return (Student)obj;
    }
}

public class CloneEx {
    public static void main(String[] args) {
        Student st = new Student(3, "홍길동");
        Student stCopy = st.clone(); // 형변환 필요 X
        System.out.println(st);
        System.out.println(stCopy);
    }
}

✔️ 얕은 복사(shallow copy)

1. 특징

(1) 원본과 복사본이 같은 객체를 공유
(2) 원본을 변경하면 복사본도 영향을 받음


✔️ 깊은 복사(deep copy)

1. 특징

(1) 원본이 참조하고 있는 객체까지 복사
(2) 원본을 변경해도 복사본에 영향이 없음

2. 예시

public class University implements Cloneable {
    private Student st;
    private String name;

    public University deepCopy() { // 깊은 복사
        Object obj = null;
        try {
            obj =  super.clone();
        } catch (CloneNotSupportedException e) {}
        University uni = (University) obj;
        // 복제된 객체가 새로운 Student 인스턴스를 참조하도록 하였고, 새 인스턴스를 만들 때 값을 복사해서 넘기면 됨
        uni.setStudent(new Student(this.st.getGrade(), this.st.getName());
        
        return uni;
    }
}

public class CloneEx {
    public static void main(String[] args) {
    University uni1 = new University(new Student(3, "홍길동"), "서울대학교");
    University uni2 = uni1.clone();

    // clone한 University의 Student grade를 3 -> 4로 변경
    uni2.getStudent().setGrade(4);

    System.out.println(uni1);
    System.out.println(uni2);
    }
}

위 내용은 다음 블로그를 참고하였습니다

profile
2023.09 ~ 티스토리 이전 / 2024.04 ~ 깃허브 블로그 이전

0개의 댓글