instanceof๋?
๐ instanceof๋ ๊ฐ์ฒด๊ฐ ํน์ ํด๋์ค ๋๋ ์ธํฐํ์ด์ค์ ์ธ์คํด์ค์ธ์ง ํ์ธํ๋ ํค์๋
๐ ์ฆ, ์ด๋ค ๊ฐ์ฒด๊ฐ ํน์ ํ์
์ ์ธ์คํด์ค์ธ์ง ํ๋ณํ๋ ๋ฐ ์ฌ์ฉ๋จ
1. instanceof ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
if (๊ฐ์ฒด instanceof ํด๋์ค๋ช
) {
// ๊ฐ์ฒด๊ฐ ํด๋น ํด๋์ค์ ์ธ์คํด์ค๋ผ๋ฉด ์คํ
}
String text = "Hello";
if (text instanceof String) {
System.out.println("โ
text๋ String ํ์
์
๋๋ค!");
}
โก ์ถ๋ ฅ: โ
text๋ String ํ์
์
๋๋ค!
โก text๊ฐ String์ ์ธ์คํด์ค์ด๋ฏ๋ก true
2. instanceof ํ์ฉ ์์
(1) ๋ถ๋ชจ ํด๋์ค์ ์์ ํด๋์ค ํ๋ณ
class Animal {}
class Dog extends Animal {}
public class InstanceofExample {
public static void main(String[] args) {
Animal a = new Dog();
if (a instanceof Dog) {
System.out.println("โ
a๋ Dog ํ์
์
๋๋ค!");
}
if (a instanceof Animal) {
System.out.println("โ
a๋ Animal ํ์
์
๋๋ค!");
}
}
}
์คํ ๊ฒฐ๊ณผ
โ
a๋ Dog ํ์
์
๋๋ค!
โ
a๋ Animal ํ์
์
๋๋ค!
โ a๋ Dog ์ธ์คํด์ค์ด๋ฉด์ Animal ํ์ ์ด๋ฏ๋ก ๋ ๋ค true.
3. instanceof์ null
โ null instanceof๋ ํญ์ false
String str = null;
System.out.println(str instanceof String); // false
โก null์ ์ด๋ค ํ์ ์๋ ์ํ์ง ์์ผ๋ฏ๋ก false
4. instanceof vs getClass()
- instanceof๋ ์์ ๊ด๊ณ๋ ์ฒดํฌํ์ง๋ง,
- getClass()๋ ์ ํํ ํด๋์ค๋ง ์ฒดํฌ
class Parent {}
class Child extends Parent {}
public class Test {
public static void main(String[] args) {
Parent obj = new Child();
System.out.println(obj instanceof Parent); // โ
true
System.out.println(obj instanceof Child); // โ
true
System.out.println(obj.getClass() == Parent.class); // โ false
System.out.println(obj.getClass() == Child.class); // โ
true
}
}
์ ๋ฆฌ
โ instanceof๋ ๊ฐ์ฒด๊ฐ ํน์ ํด๋์ค(๋๋ ์ธํฐํ์ด์ค)์ ์ธ์คํด์ค์ธ์ง ํ๋ณ
โ null instanceof๋ ํญ์ false
โ ๋ถ๋ชจ-์์ ๊ด๊ณ๋ ์ฒดํฌ ๊ฐ๋ฅ (Dog๋ Animal์ ์ธ์คํด์ค์)
โ getClass()์ ๋ค๋ฅด๊ฒ instanceof๋ ์์ ๊ด๊ณ๊น์ง ์ฒดํฌ
'Category > Java' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA] var๋? (0) | 2025.02.27 |
---|---|
[JAVA] ๋๋ค ํํ์(Lambda Expression)๊ณผ ๋ฉ์๋ ์ฐธ์กฐ(Method Reference) (0) | 2025.01.12 |
[JAVA] ๋ฐ๋ณต๋ฌธ ์ ๋ฆฌ (0) | 2025.01.12 |