백엔드/JAVA
ch06. 타입변환과 다형 8/22
372_
2024. 8. 28. 21:48
public class UpcastingDowncastingDemo {
public static void main(String[] args) {
Person p = new Person();
Student s = null;
//String s = p; // 부모와 자식 으로써 서로 타입이 다름
Student s = (Student) p; // 클래스를 casting하다가 person과 Student의 형식이 맞지않음
}
}
public static void main(String[] args) {
Student s = new Student();
Person p = new Person();
System.out.println(s instanceof Student);
System.out.println(s instanceof Person);
System.out.println(s instanceof Object);
}
public static void main(String[] args) {
Student s = new Student();
Person p = new Person();
Army a = new Army();
downcast(s);
downcast(p);
// downcast("abdfdfe");
downcast(a);
}
private static void downcast(Person p) {
if (p instanceof Army) {
Army a = (Army) p;
System.out.println(a.number);
a.work();
}
}
반응형