Java에서 instanceof 키워드의 사용법 요약
package com.instanceoftest;
interface A{}
class B implements A{
}
class C extends B {
}
class instanceoftest {
public static void main(String[] args){
A a=null;
B b=null;
boolean res;
System.out.println("instanceoftest test case 1: ------------------");
res = a instanceof A;
System.out.println("a instanceof A: " + res);
res = b instanceof B;
System.out.println("b instanceof B: " + res);
System.out.println("
instanceoftest test case 2: ------------------");
a=new B();
b=new B();
res = a instanceof A;
System.out.println("a instanceof A: " + res);
res = a instanceof B;
System.out.println("a instanceof B: " + res);
res = b instanceof A;
System.out.println("b instanceof A: " + res);
res = b instanceof B;
System.out.println("b instanceof B: " + res);
System.out.println("
instanceoftest test case 3: ------------------");
B b2=(C)new C();
res = b2 instanceof A;
System.out.println("b2 instanceof A: " + res);
res = b2 instanceof B;
System.out.println("b2 instanceof B: " + res);
res = b2 instanceof C;
System.out.println("b2 instanceof C: " + res);
}
}
/*
result:
instanceoftest test case 1: ------------------
a instanceof A: false
b instanceof B: false
instanceoftest test case 2: ------------------
a instanceof A: true
a instanceof B: true
b instanceof A: true
b instanceof B: true
instanceoftest test case 3: ------------------
b2 instanceof A: true
b2 instanceof B: true
b2 instanceof C: true
instanceof는 Java의 이원 조작부호로 ==,>, <와 같은 종류이다.이것은 알파벳으로 구성되어 있기 때문에 자바의 보존 키워드이기도 하다.그것의 역할은 왼쪽의 대상이 오른쪽의 클래스의 실례인지 테스트하고boolean 형식의 데이터를 되돌려주는 것이다.용법: 어떤 실례 대상 instance of 어떤 클래스 이름
instanceof는 일반적으로 다양한 인스턴스에 따라 다른 방법을 호출하는 데 사용됩니다.
첫째, 계승 관계가 있는 클래스에서 우리는 여러 가지 사례를 통해 서로 다른 방법을 호출할 수 있다.
예1:
세 가지 종류가 있는데, 종류와 그것들 사이의 관계는 다음과 같다.
Animal (Superclass) Dog(Subclass) Cat(Subclass)
다음과 같은 객체를 얻을 수 있습니다.
Animal animal =new Animal (); ====》animal instance of 애니멀
Dog dog=new Dog();====》dog instanceof Dog 반환true
Cat cat=new Cat();====》cat instanceof Cat 반환true
Animal dog=new Dog();====》dog instance of Animal 반환true
Animal cat=new Cat();====》cat instance of Animal 반환true
Animal dog=new Dog();
Animal cat=new Cat();
List list = new ArrayList();
list.add(dog);
list.add(cat);
Iterator it = list.iterator();
while (it.hasNext()) {
it.next().animalDo();
}
여기서 우리는 Dog와 Cat 클래스에서 Animal의 animalDo 방법을 다시 쓸 수 있다. animalDo 방법을 호출하면 서로 다른 실례에 따라 다른 클래스의 방법을 자동으로 호출할 수 있다.둘째, 계승 관계가 없는 클래스에서 우리는 instanceof를 통해 현재 실례를 판단하고 서로 다른 실례에 따라 다른 방법을 호출할 수 있다.
예2:
Station s = new Station();
Cell c = new Cell();
List list = new ArrayList();
list.add(s);
list.add(c);
Iterator it = list.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (obj instanceof Station ) {
Station s1 = (Station ) obj;
s1.stationDo();
}
if (obj instanceof Cell ) {
Cell c1 = (Cell ) obj;
c1.cellDo();
}
}
여기서 우리는 instanceof 판단 결과를 통해 서로 다른 종류의 상응하는 동작 방법(station Do(),cell Do()을 실행할 수 있다.일반적으로 무범형 집합(List, set 등)을 사용할 때 instanceof를 많이 사용하는데 집합은 여러 가지 대상을 저장할 수 있기 때문에 읽을 때 상응하는 판단을 해야 한다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.