내부 속성이 똑같은 두 클래스간의 캐스팅 테스트

Prototype 패턴 발표중에 Object의 clone()메서드는 Object 타입으로 업캐스팅하여 복사한 다음 Object 클래스를 반환한다는점에서 클래스는 다르지만 내부 프로퍼티 , 메서드 모두 같으면 캐스팅이 되는지에 대한 궁금증을 해결하고자 작성한 실험 글.

public class TestChild {
    private String name;
    public TestChild(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

public class Test2 implements Cloneable {
    private String name;
    public Test2(String name) {
        this.name = name;
    }
    @Override
    public TestChild clone() {
        TestChild clone = (TestChild) super.clone();
        return clone;
    }
}

public static void main(String[] args) throws CloneNotSupportedException {
        Test2 test2 = new Test2("test2");
        TestChild testChild2 = test2.clone();
        System.out.println(testChild2.getName());
}

//결과
//ClassCastException 발생
public class Child1 {
    private String name;
    public Child1(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
public class Child2 implements Cloneable{
    private String name;
    public Child2(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

}

public class Study {
    public static void main(String[] args) throws CloneNotSupportedException {
        Child2 child2 = new Child2("child2");
        Child1 child1 = (Child1) child2.clone();
        System.out.println(child1.getName());
    }
}

//결과
//ClassCastException 발생

Last updated