Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

보근은 참고 있다

자바의 Upcasting과 Downcasting 본문

Language/자바

자바의 Upcasting과 Downcasting

보근 2021. 7. 18. 14:07

 

 

 

 

 

 

Upcasting은 하위 클래스의 오브젝트를 상위 클래스 타입으로 선언하는 것이다.

  • 하위 클래스들은 상위 클래스의 속성들을 상속받기 때문에 상위 클래스의 멤버 변수나 메소드에 접근할 수 있다. 
  • 그렇기 때문에 Upcasting은 따로 명시를 하지 않는 암묵적인 형변환허용한다.

 

Downcasting은 상위 클래스의 오브젝트를 하위 클래스 타입으로 선언하는 것이다.

  • 상위 클래스들은 하위 클래스의 속성들을 상속받지 않을 수도 있기 때문에 멤버 변수나 메소드에 접근할 수 없다.
  • 그렇기 때문에 Downcasting은 암묵적인 형변환허용되지 않는다.

 

 

 

 

 

Parent p = new Child();           //  Upcasting으로 Child 인스턴스가 Parent 타입으로 선언됨.
Child c = (Child) p;              //  Downcasting으로 Child 타입으로 선언됨.

System.out.println(p.pMember);    //  정상 출력.
System.out.println(c.pMember);    //  정상 출력.
System.out.println(c.cMember);    //  정상 출력.
System.out.println(p.cMember);    //  컴파일 에러.

System.out.println((Child p).cMember); // 정상출력.

p.pMethod();                      //  정상 동작.
c.pMethod();                      //  정상 동작.
c.cMethod();                      //  정상 동작.
p.cMethod();                      //  컴파일 에러.

(Child p).cMethod();              //  정상 동작.

위의 예시를 보면, Child 인스턴스를 갖고 있는 Parent 객체를 다시 Child 타입으로 Downcasting이 가능하다.

 

 

 

Parent p = new Parent();
Child c = (Child) p;            //  ClassCastException 발생.

Downcasting이 가능한 조건이 아니라면 예외가 발생한다.

 

 

 

 

 

Parent p = new Child("Hello", 10);
Child c = (Child) p;

System.out.println(p.pMember);      //  Hello 출력.
System.out.println(c.pMember);      //  Hello 출력.
System.out.println(c.cMember);      //  10 출력.

같은 인스턴스를 참조하기 때문에 당연하게도, 위와 같은 결과가 나온다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

'Language > 자바' 카테고리의 다른 글

String vs StringBuilder vs StringBuffer  (0) 2021.07.17
Functional Interface  (0) 2020.11.01
Stream  (0) 2020.10.31
Optional  (0) 2020.10.31
SOLID (객체 지향 설계 원칙)  (0) 2020.10.28
Comments