JAVA
221013 instanceof
주영재
2022. 10. 13. 10:17
클래스 타입 확인! instanceof 키워드
+)쓸 일은 거의 없긴 함...
객체-instance
instanceof는 boolean으로 값이 나온다
객체가 지정한 클래스의 인스턴스인지 아닌지 검사하는 키워드.
Person p = new Student();
p instanceof Student>true
p instanceof Person>true
p instanceof Teacher>false
package day08.poly.instanceof_;
public class MainClass {
public static void main(String[] args) {
//instanceof-객체의 모형을 확인
Person s=new Student("홍길동",10,"1234");
Person t =new Teacher("이순신",20,"프로그램");
casting(s);
casting(t);
}
public static void casting(Person p) {
if(p instanceof Student) {//p가 Student라면 true, 아니면 false
Student s =(Student)p;
System.out.println(s.info());
}else if(p instanceof Teacher) {
Teacher t = (Teacher)p;
System.out.println(t.info());
}
}
}
이름:홍길동, 나이:10, 학번:1234
이름:이순신, 나이:20, 과목:프로그램
Casting 메서드는 Person p에 받는 객체를 instance of로 검사해서 원하는 객체와 맞다면 실행, 아니면 실행하지 않음