
์ค๋ฅธ์ชฝ ํ์ ์ ์ผ์ชฝ์ ์๋ ์ธ์คํด์ค์ ํ์ ์ด ๋ค์ด๊ฐ ์ ์๋์ง ๋์ ํด๋ณด๋ฉด ๋๋ค.
[ ์ธ์คํด์ค + instanceof + ๊ฐ์ฒด ํ์ ]
๋์ ์ด ๊ฐ๋ฅํ๋ฉด true, ๋ถ๊ฐ๋ฅํ๋ฉด false๊ฐ ๋๋ค.
new Parent() instanceof Parent
Parent p = new Parent() - ๊ฐ์ ํ์ true
new Child() instanceof Parent
Parent p = new Child() - ๋ถ๋ชจ๋ ์์์ ๋ด์ ์ ์๋ค. true
new Parent() instanceof Child
Child c = new Parent() - ์์์ ๋ถ๋ชจ๋ฅผ ๋ด์ ์ ์๋ค . false
new Child() instanceof Child
Child c = new Child() - ๊ฐ์ ํ์ true
instanceof๋ Java์์ ๊ฐ์ฒด๊ฐ ํน์ ํด๋์ค๋ ์ธํฐํ์ด์ค์ ์ธ์คํด์ค์ธ์ง ํ์ธํ๋ ๋ฐ ์ฌ์ฉ๋๋ ์ฐ์ฐ์์ด๋ค.
์ฃผ๋ก ๊ฐ์ฒด์ ๋ฐํ์ ํ์ ์ ํ์ธํ๊ฑฐ๋ ํ์ ์บ์คํ ์ ์ ์์ ์ฑ์ ๊ฒ์ฌํ๋ ๋ฐ ์ฌ์ฉ๋๋ค.
๊ตฌ๋ฌธ
object instanceof ClassName
• object: ๊ฒ์ฌํ๋ ค๋ ๊ฐ์ฒด
• ClassName: ๊ฒ์ฌํ ๋์ ํด๋์ค๋ ์ธํฐํ์ด์ค
๊ฒฐ๊ณผ
• true: object๊ฐ ClassName ๋๋ ๊ทธ ํ์ ํด๋์ค์ ์ธ์คํด์ค์ด๋ฉด
• false: ๊ทธ๋ ์ง ์์ผ๋ฉด
์ค๋ช ๋ฐ ์์
1. ๊ฐ์ ํ์ ์ผ ๊ฒฝ์ฐ:
Parent p = new Parent();
System.out.println(p instanceof Parent); // true
• Parent ํด๋์ค์ ์ธ์คํด์ค๋ ๋น์ฐํ Parent ํ์ ์ด๋ฏ๋ก true.
2. ๋ถ๋ชจ ํ์ ์ผ๋ก ์์์ ๊ฐ๋ฆฌํค๋ ๊ฒฝ์ฐ:
Parent p = new Child();
System.out.println(p instanceof Parent); // true
• Child๋ Parent๋ฅผ ์์๋ฐ์์ผ๋ฏ๋ก, ๋ถ๋ชจ ํ์ (Parent) ๋ณ์๋ก ์์ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ ์ ์์ต๋๋ค.
• ๋ฐ๋ผ์ Child ๊ฐ์ฒด๋ Parent ํ์ ์ผ๋ก ๊ฐ์ฃผ๋์ด true.
3. ์์ ํ์ ์ผ๋ก ๋ถ๋ชจ๋ฅผ ๊ฐ๋ฆฌํค๋ ค๋ ๊ฒฝ์ฐ:
Parent p = new Parent();
System.out.println(p instanceof Child); // false
• Parent ๊ฐ์ฒด๋ Child ํ์ ์ด ์๋๋ฏ๋ก false.
4. ๊ฐ์ ์์ ํ์ ์ผ ๊ฒฝ์ฐ:
Child c = new Child();
System.out.println(c instanceof Child); // true
• Child ํด๋์ค์ ๊ฐ์ฒด๋ ๋น์ฐํ Child ํ์ ์ด๋ฏ๋ก true.
5. ์ธํฐํ์ด์ค์ ํจ๊ป ์ฌ์ฉํ๋ ๊ฒฝ์ฐ:
interface MyInterface {}
class Parent implements MyInterface {}
Parent p = new Parent();
System.out.println(p instanceof MyInterface); // true
• Parent๊ฐ MyInterface๋ฅผ ๊ตฌํํ์ผ๋ฏ๋ก, p๋ MyInterface ํ์ ์ผ๋ก ๊ฐ์ฃผ๋ ์ ์๋ค.
์ค์ ํฌ์ธํธ
1. ์์ ๊ด๊ณ์ ๋์ ๊ฐ๋ฅ์ฑ์ ๊ธฐ๋ฐ:
• instanceof๋ ๊ฐ์ฒด๊ฐ ํด๋น ํ์ ์ผ๋ก ๋์ ๊ฐ๋ฅํ์ง๋ฅผ ํ๋จํ๋ค.
• ๋ถ๋ชจ๋ ์์์ ์ฐธ์กฐํ ์ ์์ง๋ง, ์์์ ๋ถ๋ชจ๋ฅผ ์ฐธ์กฐํ ์ ์๋ค.
2. null์ ํญ์ false:
Parent p = null;
System.out.println(p instanceof Parent); // false
• null์ ์ด๋ค ํด๋์ค ํ์ ์๋ ์ํ์ง ์์ผ๋ฏ๋ก false.
3. ์ปดํ์ผ ์์ vs ๋ฐํ์ ์์ :
• instanceof๋ ๋ฐํ์์ ๊ฐ์ฒด์ ํ์ ์ ํ์ธํ๋ค.
• ์ปดํ์ผ ์์ ์๋ ํ์ ๊ฒ์ฌ๊ฐ ์ด๋ฃจ์ด์ง์ง ์๋๋ค.
์ ๋ฆฌ
instanceof๋ ๋ค์๊ณผ ๊ฐ์ ์ํฉ์์ ์ ์ฉํ๋ค:
• ํ์ ์์ ์ฑ์ ๋ณด์ฅํ๊ณ ์ ํ ๋
• ๋ค์ด์บ์คํ ์ด ๊ฐ๋ฅํ์ง ํ์ธํ๊ณ ์ถ์ ๋
• ๋คํ์ฑ(polymorphism)๊ณผ ๊ด๋ จ๋ ์ฝ๋์์ ๋ฐํ์ ํ์ ์ ํ๋ณํ๊ณ ์ ํ ๋
if (p instanceof Child) {
Child c = (Child) p;
// ์์ ํ๊ฒ ๋ค์ด์บ์คํ
ํ์ฌ ์ฌ์ฉ ๊ฐ๋ฅ
}