11. Reference Type Casting
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | class Super{ public void superMethod(){ System.out.println("Super : superMethod()"); } // end of superMethod } // end of Super class Sub extends Super{ public void superMethod(){ System.out.println("Overried Sub : superMethod()"); } // end of superMethod public void subMethod(){ System.out.println("sub : subMethod()"); } // end of subMethod } // end of sub public class CastingComplete{ public static void main(String [] args){ // 상위 class Instance 생성 (Data Type 과 Instance가 같을 때) System.out.println("\nSuper s1 = new Super()"); Super s1 = new Super(); s1.superMethod(); // 하위 class Instance 생성 (Data Type 과 Instance가 같을 때) System.out.println("\nSub = new sub()"); Sub s2 = new Sub(); s2.superMethod(); s2.subMethod(); // 상위 Data Type으로 하위 Instance 생성 (Date Type 과 Instance가 다를 때) System.out.println("\nSuper s3 = new sub()"); Super s3 = new Sub(); s3.superMethod(); // call overriden method // 하위 Instance를 참조하는 상위 Data Type은 하위 Data Type의 Method들을 사용 할 수 없다. // 그러나 하위 Data Type에 Override된 Method들을 사용할 수 있다. // s3.subMethod(); => Impossible // 사용하기 위해서는 Explicit Casting을 하도록 한다. (Sub)s3.subMethod(); // Impossible ((Sub)s3).subMethod(); // Possible System.out.println("\nCasting"); Sub sub = (Sub)s3; sub.subMethod(); // 이 Data Type이 사용 되는 목적은 하위에 Override된 Method들만을 사용할 때다. // 하위 Data Type으로 상위 Instance 생성(Data Type과 Instance가 다를 때) Sub s4 = new Super(); // Casting error Sub s4 = ((Sub) new Super()); // ClassCastException } // end of main } // end of CastingComplete | cs |
반응형
'Java > Theory' 카테고리의 다른 글
[Java/Theory]13. null, Garbage collection (0) | 2016.05.31 |
---|---|
[Java/Theory]12. Access Modifier (0) | 2016.05.30 |
[Java/Theory]10. API (0) | 2016.05.30 |
[Java/Theory]09. Import (0) | 2016.05.30 |
[Java/Theory]08. Package (0) | 2016.05.30 |