Skip to content

Commit

Permalink
[Week3][Chap10] 캐스팅의 종류 (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
arinming committed Jan 31, 2024
1 parent e05edaf commit ce669c2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
19 changes: 19 additions & 0 deletions 김아린/java-basic/src/poly/basic/CastingMain2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package poly.basic;

public class CastingMain2 {
public static void main(String[] args) {
// 부모 변수가 자식 인스턴스 참조(다형적 참조)
Parent poly = new Child();

// 단, 자식의 기능은 호출 불가, 컴파일 오류 발생
// poly.childMethod();

// 다운 캐스팅(부모 타입 -> 자식 타입)
Child child = (Child) poly; // x001
child.childMethod();

// 일시적 다운 캐스팅 - 해당 메서드를 호출하는 순간만 다운 캐스팅
((Child) poly).childMethod();

}
}
13 changes: 13 additions & 0 deletions 김아린/java-basic/src/poly/basic/CastingMain3.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package poly.basic;

// upcasting vs downcasting
public class CastingMain3 {
public static void main(String[] args) {
Child child = new Child();
Parent parent1 = (Parent) child; // 업캐스팅은 생략 가능, 생략 권장
Parent parent2 = child; // 업캐스팅 생략

parent1.parentMethod();
parent2.parentMethod();
}
}

0 comments on commit ce669c2

Please sign in to comment.