Skip to content

Commit

Permalink
[Week3][Chap10] 캐스팅 종류 - 업캐스팅 시작 (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
toychip committed Feb 13, 2024
1 parent cb4af2e commit 5d18093
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package week3.poly.basic;

public class CastingMain2 {
public static void main(String[] args) {
// 부모 변수가 자식 인스턴스 참조(다형적 참조)
Parent poly = new Child(); // x001
// 단 자식의 기능은 호출할 수 없다.
// poly.childMethod() // compile error!!

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

// 일시적 다운 캐스팅 - 해당 메서드를 호출하는 순간만 다운캐스팅
((Child) poly).childMethod();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package week3.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 5d18093

Please sign in to comment.