Skip to content

Commit

Permalink
[Week3][Chap10] instanceof (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
toychip committed Feb 13, 2024
1 parent 06773f4 commit 19abd30
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package week3.poly.basic;

// 다운캐스팅을 자동으로 하지 않는 이유
public class CastingMain5 {

public static void main(String[] args) {
Parent parent1 = new Parent();
call(parent1);
System.out.println("-------------");

Parent parent2 = new Child();
call(parent2);
}

private static void call(Parent parent) {
parent.parentMethod();

if (parent instanceof Child) {
System.out.println("Child 인스턴스 맞음");
Child child = (Child) parent;
child.childMethod();
} else {
System.out.println("Child 인스턴스 아님");
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package week3.poly.basic;

// 다운캐스팅을 자동으로 하지 않는 이유
public class CastingMain6 {

public static void main(String[] args) {
Parent parent1 = new Parent();
call(parent1);
System.out.println("-------------");

Parent parent2 = new Child();
call(parent2);
}

private static void call(Parent parent) {
parent.parentMethod();

if (parent instanceof Child child) {
System.out.println("Child 인스턴스 맞음");
child.childMethod();
} else {
System.out.println("Child 인스턴스 아님");
}
}

}

0 comments on commit 19abd30

Please sign in to comment.