CodeGym /행동 /자바 코어 /instanceof 연산자

instanceof 연산자

자바 코어
레벨 4, 레슨 1
사용 가능

"안녕하세요, 아미고! 당신은 이미 instanceof 연산자를 만났습니다. 오늘은 그것이 어디에 어떻게 사용될 수 있는지 알려드리겠습니다. instanceof 는 매우 간단하고 효율적인 연산자입니다."

"광고 같아!"

"정말 간단합니다. 다음과 같이 사용됩니다. «object» instanceof «class» ."

개체가 특정 클래스의 인스턴스인지 확인합니다. 그것을 설명하는 것보다 쉽습니다. 이 예를 살펴보십시오.

암호 설명
Object o = new Integer(3);
boolean isInt = o instanceof Integer;
isInt 는 true 입니다 . 변수 o가 참조하는 개체는 Integer 클래스의 인스턴스입니다.
Object o = "Mama";
boolean isInt = o instanceof Integer;
isInt 는 false 입니다 . 변수 o가 참조하는 개체는 Integer 클래스의 인스턴스가 아닙니다. 문자열 개체 입니다 .
InputStream is = new FileInputStream("");
boolean isFIS = is instanceof FileInputStream;
isFIS는 사실 일 것입니다 . 변수 o가 참조하는 개체는 FileInputStream 클래스의 인스턴스입니다.

"예, 아주 간단합니다."

"이 연산자는 상속도 고려합니다. 확인하십시오."

암호 설명
class Animal
{
}
class Cat extends Animal
{
}
class Tiger extends Cat
{
}
여기에는 Animal, Cat 및 Tiger의 세 가지 클래스 선언이 있습니다. 고양이는 동물을 물려받습니다. 그리고 Tiger는 Cat을 물려받습니다.
Object o = new Tiger();
boolean isCat = o instanceof Cat;
boolean isTiger = o instanceof Tiger;
boolean isAnimal = o instanceof Animal;
isCat은 true  입니다  .
isTiger는 사실  일 것입니다  .
isAnimal은 true  입니다  .
Object o = new Animal();
boolean isCat = o instanceof Cat;
boolean isTiger = o instanceof Tiger;
boolean isAnimal = o instanceof Animal;
isCat은 false  입니다 .
isTiger 는 false  입니다  .
isAnimal은 true  입니다  .

그리고 심지어 인터페이스:

암호 설명
interface Moveable
{
}
class Cat
{
}
class TomCat extends Cat implements Moveable
{
}
두 개의 클래스 만들기: Cat, TomCat 및 Moveable 인터페이스
Cat o = new TomCat();
boolean isCat = o instanceof Cat;
boolean isMoveable = o instanceof Moveable;
boolean isTom = o instanceof TomCat;
isCat은 true  입니다  .
isMovable 이 true  됩니다  .
isTom은 사실  입니다  .
Cat o = new Cat();
boolean isCat = o instanceof Cat;
boolean isMoveable = o instanceof Moveable;
boolean isTom = o instanceof TomCat;
isCat은 true  입니다  .
isMovable 은 false  입니다  .
isTom은 false  입니다  .

instanceof 연산자는 다음과 같습니다: a instanceof B .

즉, instanceof 연산자는 다음과 같은 경우 true를 반환합니다 .

1) 변수 a는 유형 B 의 객체에 대한 참조를 저장합니다.

2)  변수 a는 클래스가 B 를 상속하는 객체에 대한 참조를 저장합니다. 

3)  변수 a는 인터페이스 B 를 구현하는 객체에 대한 참조를 저장합니다. 

그렇지 않으면 instanceof 연산자는 false 를 반환합니다 .

"알았어. 그럼 이게 왜 필요한거야, 리시 아저씨?"

"오늘 Ellie가 그 이야기를 들려줄 것입니다. 그는 정말 훌륭한 오퍼레이터입니다. 오늘은 그것을 확신하게 될 것입니다."

4
과제
자바 코어, 레벨 4, 레슨 1
잠금
Code entry
Sometimes you don't need to think, you just need to hammer it out! As paradoxical as it may seem, sometimes your fingers will "remember" better than your conscious mind. That's why while training at the secret CodeGym center you will sometimes encounter tasks that require you to enter code. By entering code, you get used to the syntax and assimilate some material. What's more, you combat laziness.
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION