[IT]/java
java.Polymorphism.instanceof(객체 타입 비교)
givemebro
2021. 3. 2. 16:33
반응형
instanceof : 객체의 타입을 비교하는 연산자
> is a 관계가 성립 : true / 아니면 false
예제1
package step12;
import step11.Monkey;
import step11.Person;
public class TestInstanceof {
public static void main(String[] args) {
ZooService2 service = new ZooService2();
// import 단축키 : ctrl + shift + o
service.pass(new Person());
service.pass(new Monkey());
}
}
/*
나는 사람이다
나는 원숭이다
*/
package step12;
import step11.Animal;
import step11.Monkey;
import step11.Person;
public class ZooService2 {
public void pass(Animal a) {
// TODO Auto-generated method stub
// 자식 > 부모 순으로 비교
if (a instanceof Person) {
System.out.println("나는 사람이다");
} else if (a instanceof Monkey) {
System.out.println("나는 원숭이다");
} else if (a instanceof Animal) {
System.out.println("나는 동물이다");
}
}
}
java.Polymorphism(다형성)
Polymorphism(다형성): Polymorphism은 객체 지향의 주요 개념 "하나의 메세지 방식으로 다향한 객체들이 각자의 방식으로 동작하는 성질" "One Interface, Multiple Implements" > 다형성 적용을 위해서는 계층..
broscoding.tistory.com
반응형