ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Object 클래스(3) - clone()
    수정중/수정중2 2023. 2. 3. 23:32

    clone() 메서드

    • 객체의 원본을 복제하는데 사용하는 메서드
    • 어떤 인스턴스에 대해 작업을 할 때, 원래의 인스턴스는 보존하고 clone 메서드를 이용해서 새로운 인스턴스를 생성하여 작업을 하면, 작업 이전의 값이 보존되므로 작업에 실패해서 원래의 상태로 되돌릴 때 쓰면 된다. 

    clone() 메서드 구현

    • 먼저, 아래와 같이 s1을 클론해보자. 오류가 뜬다. 클론하려는 클래스인 Student가 클론이 가능한 것인지 모르기 때문이다. 해당 클래스의 clone() 메서드의 사용을 허용한다는 의미로 cloneable 인터페이스를 써줘야 한다. ex) implements Cloneable
    • 참고로 Cloneable 인터페이스는 비어 있다. 아무것도 없다. 비어 있는 인터페이스를 왜 구현할까? 단지 복제 가능한 클래스라는 걸 JVM에게 알려주기 위해서다. 
    package org.opentutorials.javatutorials.progenitor;
    
    class Student implements Cloneable  // 2. Student 클래스는 복제가 가능한 클래스구나
    	String name;
        
        Student(String name) {
        	this.name = name;
            }
     }
     
     public class ObjectDemo {
     	public static void main(String[] args) {
        	Student s1 =  new Student("egoing");
            s1.clone();  // 1. Student 클래스는 복제가 가능한가?
            
            }
     }
    • cloneable을 적어줬는데 또 에러가 난다. 왜? clone의 접근제어자가 protected라
    package org.opentutorials.javatutorials.progenitor;
    
    class Human {
    	protected String test() {
        	return "test";
            }
    }
    
    class Student exteds Human implements Cloneable { 
    	String name;
        
        Student(String name) {
        	this.name = name;
            }
    }
     
     public class ObjectDemo {
     	public static void main(String[] args) {
        	Student s1 =  new Student("egoing");
            s1.test();  // 
            
            }
    }

     

     

    class Student implements Cloneable {
    	String name;
        Student(String name) {
        	this.name = name;
            }
        protedcted Object clone() throw CloneNotSupportedException {
        	return suer.clone();
            }
        }
    • 생성과정의 복잡한 과정을 반복하지 않고 복제 할 수 있음(vs 생성자: 생성자는 초기화값을 가지지만 clone은 중간에변한 값을 그대로 복제함)
    • clone()메서드를 사용하면 객체의 정보(멤버 변수 값등...)가 동일한 또 다른 인스턴스가 생성되는 것이므로, 객체 지향 프로그램에서의 정보 은닉, 객체 보호의 관점에서 위배될 수 있음
    • 해당 클래스의 clone() 메서드의 사용을 허용한다는 의미로 cloneable 인터페이스를 명시해 줌
    • ex) implements Cloneable
    • clone 메소드는 접근제어자가 protected라 clone()메서드를 사용하면 객체의 정보(멤버 변수 값등...)가 동일한 또 다른 인스턴스가 생성되는 것이므로, 객체 지향 프로그램에서의 정보 은닉, 객체 보호의 관점에서 위배될 수 있음

    class Student implements Cloneable  // 2. Student 클래스는 복제가 가능한 클래스구나
    	String name;
        
        Student(String name) {
        	this.name = name;
            }
     }
     
     public class ObjectDemo {
     	public static void main(String[] args) {
        	Student s1 =  new Student("egoing");
            s1.clone();  // 1. Student 클래스는 복제가 가능한가?
            
            }
     }

    그 다음,

    class Human{
    	protected String test() { 
        return "test";
        }
      }
      
    class Student extends Human implements Cloneable{
    	String name;
        Student(String name) {
        	this.name = name;
            }
       }
       
    public class ObjectDemo {
    	publi static void main(String[] args) {
        Student s1 = new Student("egoing");
        s1.test();
        }
     }

     

     

    Student.java

    public class Student implements Cloneable{
    
        .......
    
    	@Override
    	protected Object clone() throws CloneNotSupportedException {
    		
    		return super.clone();  // 그냥 클론할거면 Object의 메소드만 해도 된다.
    	}
    }

    EqualTest.java

        Student Lee3 = (Student)Lee.clone();
    	System.out.println(System.identityHashCode(Lee));
    	System.out.println(System.identityHashCode(Lee3));
    		
    • 클론의 리턴타입은 Object라서 반드시 자식 클래스에 접근하려면 형변환은 해줘야 한다. 
    •  

    댓글

Designed by Tistory.