티스토리 뷰

▶마커 인터페이스(Marker Interface)에 대해 알아보자

 

🔎 마커 인터페이스(Marker Interface) ?


마커 인터페이스란

인터페이스 내부에 상수도, 메소드도 없는 인터페이스를 말합니다.

 

아무 내용도 없어서 쓸모가 없어보이지만,,

마커 인터페이스는 클래스들을 그룹화하기 위한 목적으로 사용하는데요.

 

📌 예시 코드

package markerInterfaceTest;

public class Animal {;}

public class Bear extends Animal {;}
public class Cow extedns Animal {;}
public class Dog extends Animal {;}
public class Tiger extends Animal {;}

위와 같이 Animal이라는 부모 클래스를 두고 4가지 동물 클래스에 상속해 주었는데요.

이때 만약에 육식동물, 초식동물, 잡식동물로 분류를 하고 싶다면 어떻게 해야할까요?

 

이때 바로 그룹화를 하기 위해 마커 인터페이스를 사용하는 것인데요.

package markerInterfaceTest;

public interface CarnivoreMarker {;} // 육식동물을 그룹화할 마커 인터페이스
public interface HerbivoreMarker {;} // 초식동물을 그룹화할 마커 인터페이스

이렇게 마커 인터페이스를 선언해주고 상속해주었던 코드를 수정합니다.

package markerInterfaceTest;

public class Animal {;}

public class Bear extends Animal implements CarnivoreMarker {;}
public class Cow extedns Animal implements HerbivoreMarker {;}
public class Dog extends Animal {;}
public class Tiger extends Animal implements CarnivoreMarker {;}

 

이제 메인 메소드에서 그룹화가 잘 되었는지 확인해봅시다.

package markerInterfaceTest;

public class Test {
    public void checkKinds(Animal[] animals) {
        for (int i=0; i<animals.length; i++) { // 반복문을 돌면서 타입을 확인한다.
            if(animals[i] instanceof CarnivoreMarker) {
                System.out.println("육식동물");
            } else if (animals[i] instanceof HerbivoreMarker) {
                System.out.println("초식동물");
            } else {
                System.out.println("잡식동물");
            }
        }
    }
    
    public static void main(String[] args) {
        Animal[] animals = {
            new Cow(),
            new Dog(),
            new Tiger(),
            new Bear()
        };
        
        new Test().checkKinds(animals);
    }
}

순서대로 잘 출력된 것을 확인할 수 있습니다.

출력 화면

 

728x90
LIST
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함