컴공생의 다이어리
[자바, Java] instanceof 연산자 본문
instanceof 연산자
instanceof 연산자는 원래 인스턴스의 형이 맞는지 여부를 체크하는 키워드이다. 맞으면 true 아니면 false를 반환한다.
Syntax는 아래와 같다. object가 type이거나 type을 상속받는 클래스라면 true를 리턴하고 아니면 false를 리턴한다.
object instanceOf type
아래와 같은 코드처럼 instanceof 연산자를 활용할 수 있다. parent의 경우 Parent 클래스이므로 true를 반환한다. child의 경우 Parent로부터 상속받은 클래스인 Child 클래스이므로 true를 반환한다. 하지만 parent의 경우 Parent 클래스인데 Child클래스로 비교하니 false를 반환한다. 자식은 자식이지 부모클래스가 아니기 때문이다. 마지막으로 child는 Child클래스이므로 true를 반환한다.
class Parent{}
class Child extends Parent{}
public class InstanceofTest {
public static void main(String[] args){
Parent parent = new Parent();
Child child = new Child();
System.out.println( parent instanceof Parent ); // true
System.out.println( child instanceof Parent ); // true
System.out.println( parent instanceof Child ); // false
System.out.println( child instanceof Child ); // true
}
}
https://codechacha.com/ko/java-instance-of/
Java - instanceOf 연산자
instanceOf 연산자는 객체가 어떤 클래스인지, 어떤 클래스를 상속받았는지 확인하는데 사용하는 연산자입니다. instanceOf를 어떻게 사용하고, 어떻게 동작하는지 알아보겠습니다.
codechacha.com
https://mine-it-record.tistory.com/120
[JAVA] 자바_instanceof (객체타입 확인)
instanceof - instanceof는 객체 타입을 확인하는 연산자이다. - 형변환 가능여부를 확인하며 true / false 로 결과를 반환한다. - 주로 상속 관계에서 부모객체인지 자식객체인지 확인하는데 사용된다. ins
mine-it-record.tistory.com
'Development > Java' 카테고리의 다른 글
[자바, Java] 인터페이스(interface) (0) | 2021.08.30 |
---|---|
[자바, Java] 추상 클래스(abstract class) (0) | 2021.08.29 |
[자바, Java] 캐스팅 - 업캐스팅(Upcasting), 다운캐스팅(Downcasting) (2) | 2021.08.27 |
[자바, Java] 클래스 상속(class inheritance) (0) | 2021.08.18 |
[자바, Java] ArrayList (0) | 2021.08.17 |