๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Category/Java

[JAVA] instanceof vs getClass() ์•Œ์•„๋ณด๊ธฐ

by Corinee 2025. 2. 27.
728x90
๋ฐ˜์‘ํ˜•

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๋Š” ์ƒ์† ๊ด€๊ณ„๊นŒ์ง€ ์ฒดํฌ