Notice
Recent Posts
Recent Comments
Link
반응형
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

To Be Develop

[Java] 자바 instanceof 연산자 개념: 자세한 예시 본문

dev/Java

[Java] 자바 instanceof 연산자 개념: 자세한 예시

To Be Develop 2024. 1. 29. 05:14
반응형

 

 

Java에서 instanceof 연산자는 객체가 특정 클래스의 인스턴스인지를 확인하는 데 사용됩니다. 이 연산자는 불리언 값을 반환하며, 객체가 지정된 클래스 또는 그 클래스의 하위 클래스의 인스턴스인 경우 true를 반환하고, 그렇지 않은 경우 false를 반환합니다.

 

 

instanceof 연산자는 다음과 같은 형식을 가지고 있습니다:

object instanceof Class

 

여기서 object는 검사하려는 객체이고, Class는 해당 객체가 속하는 클래스나 인터페이스입니다. 만약 objectClass의 인스턴스이거나 Class의 하위 클래스의 인스턴스이면 결과는 true이고, 그렇지 않으면 false입니다.

 

 

예를 들어, 다음은 instanceof 연산자를 사용한 간단한 예제입니다:

class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }

public class InstanceOfExample {
    public static void main(String[] args) {
        Animal dog = new Dog();
        Animal cat = new Cat();

        System.out.println(dog instanceof Animal); // true
        System.out.println(cat instanceof Animal); // true
        System.out.println(dog instanceof Dog);    // true
        System.out.println(cat instanceof Dog);    // false
    }
}

이 예제에서 DogCat 클래스는 모두 Animal 클래스의 하위 클래스입니다. 따라서 dogcat 객체는 모두 Animal 클래스의 인스턴스이기 때문에 instanceof 연산자를 사용하면 true가 반환됩니다.

 

 

더 복잡한 상황에서 instanceof를 사용하는 예제를 살펴보겠습니다. 다음은 다형성을 활용한 예제입니다.

interface Shape {
    void draw();
}

class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

class Triangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a triangle");
    }
}

public class ShapeExample {
    public static void main(String[] args) {
        Shape circle = new Circle();
        Shape rectangle = new Rectangle();
        Shape triangle = new Triangle();

        drawShape(circle);
        drawShape(rectangle);
        drawShape(triangle);
    }

    public static void drawShape(Shape shape) {
        if (shape instanceof Circle) {
            Circle circle = (Circle) shape;
            circle.draw();
        } else if (shape instanceof Rectangle) {
            Rectangle rectangle = (Rectangle) shape;
            rectangle.draw();
        } else if (shape instanceof Triangle) {
            Triangle triangle = (Triangle) shape;
            triangle.draw();
        } else {
            System.out.println("Unsupported shape");
        }
    }
}

 

이 예제에서 Shape 인터페이스를 구현한 Circle, Rectangle, Triangle 클래스가 있습니다. drawShape 메서드는 Shape를 매개변수로 받아서 해당 도형을 그리는 메서드입니다. instanceof를 사용하여 주어진 객체가 어떤 도형인지 확인하고, 해당 도형에 맞게 형변환하여 그리는 작업을 수행합니다.

또한 이 예제에서 drawShape 메서드는 Circle, Rectangle, Triangle 이외의 다른 도형을 지원하지 않는다는 가정하에 작성되었습니다. 이런 식으로 instanceof를 활용하면 다형성을 통해 여러 객체를 일관된 방식으로 처리할 수 있습니다.

반응형