Java

인터페이스

move2 2022. 11. 14. 22:14

인터페이스는 객체의 특정 행동의 특징을 정의하는 간단한 문법이다. 인터페이스는 함수의 특징(method signature)인 접근제어자, 리턴타입, 메소드 이름만을 정의한다. 함수의 내용은 없다. 인터페이스를 구현하는 클래스는 인터페이스에 존재하는 함수의 내용(중괄호 안의 내용)을 반드시 구현해야한다.

인터페이스의 형식은 다음과 같다.

interface 인터페이스명{ public abstract void 추상메서드명(); }

interface Bird {
    void fly(int x, int y, int z);
}

class Pigeon implements Bird{
    private int x,y,z;

    @Override
    public void fly(int x, int y, int z) {
        printLocation();
        System.out.println("날아갑니다.");
        this.x = x;
        this.y = y;
        this.z = z;
        printLocation();
    }
    public void printLocation() {
        System.out.println("현재 위치 (" + x + ", " + y + ", " + z + ")");
    }
}

public class Main {

    public static void main(String[] args) {
        Bird bird = new Pigeon();
        bird.fly(1, 2, 3);
//        bird.printLocation(); // compile error
    }
}

implements를 이용하여 구현한다

bird.printLocation()이 컴파일 에러가 나는 이유는 Bird타입으로 선언한 bird변수가 실제로는 Pigeon객체이지만, interface타입으로 선언되어 있는 부분은 실제 객체가 무엇이든지, interface에 정의되어 있는 행동만 할수 있기 때문이다. 따라서printLocation()는 Bird라는 interface타입에 선언되어 있지 않기 때문에 컴파일 에러가 나는 것이다.