-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |