반응형
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

bro's coding

java.Polymorphism.instanceof(객체 타입 비교) 본문

[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

 

반응형

'[IT] > java' 카테고리의 다른 글

java.abstract(추상화)  (0) 2021.03.04
java.final  (0) 2021.03.04
java.static(정적)  (0) 2021.03.04
java.Polymorphism.ObjectCasting(캐스팅)  (0) 2021.03.02
java.Polymorphism(다형성)  (0) 2021.03.02
java.annotation(어노테이션)  (0) 2021.03.02
java.overriding.toString  (0) 2021.03.02
java.Object(오브젝트 클래스)  (0) 2021.03.02
Comments