-
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.
[Week3][Chap10] 캐스팅 종류 - 업캐스팅 시작 (#26)
- Loading branch information
Showing
2 changed files
with
32 additions
and
0 deletions.
There are no files selected for viewing
17 changes: 17 additions & 0 deletions
17
임준형/java-basic/src/main/java/week3/poly/basic/CastingMain2.java
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,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(); | ||
} | ||
} |
15 changes: 15 additions & 0 deletions
15
임준형/java-basic/src/main/java/week3/poly/basic/CastingMain3.java
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,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(); | ||
} | ||
|
||
} |