Nelmm
Design Pattern
Design Pattern
  • DesignPattern 🎨
  • 객체생성
    • 싱글톤 패턴
    • 팩토리 메소드 패턴
    • 추상 팩토리 패턴
    • 빌더 패턴
    • 프로토 타입 패턴
  • 구조
    • 어댑터 패턴
    • 브릿지 패턴
    • 컴포짓 패턴
    • 데코레이터 패턴
    • 플라이웨이트 패턴
    • 퍼사드 패턴
  • 행동
    • 인터프리터 패턴
    • 커맨드 패턴
    • 이터레이터 패턴
    • 중재자 패턴
  • 추가 Issue
    • MapStruct과 ModelMapper 비교
    • Integer 객체
    • 내부 속성이 똑같은 두 클래스간의 캐스팅 테스트
Powered by GitBook
On this page
  1. 추가 Issue

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

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 발생
PreviousInteger 객체

Last updated 3 years ago