[JAVA] interface 클래스 설명, 사용 예시

2023. 1. 5. 17:43
728x90
반응형

interface 클래스 설명

Java의 인터페이스(interface)는 클래스가 구현해야 할 추상 메소드와 상수들의 집합을 정의할 수 있는 특별한 종류의 타입이다. 인터페이스를 구현(implement)한 클래스는 인터페이스가 정의한 모든 추상 메소드를 구현해야 한다.

 

인터페이스는 다음과 같이 정의할 수 있다.

interface InterfaceName {
    // 상수 정의
    int CONSTANT_VARIABLE = 0;

    // 추상 메소드 정의
    void abstractMethod();
}

 

인터페이스는 상수와 추상 메소드로만 구성될 수 있으며, 추가적인 구현을 포함할 수 없다. 인터페이스의 상수는 자동으로 public static final 접근 제한자가 적용된다. 추상 메소드는 자동으로 public abstract 접근 제한자가 적용된다.

 

인터페이스를 구현한 클래스는 다음과 같이 정의할 수 있다.

class ClassName implements InterfaceName {
    // 추상 메소드의 구현
    public void abstractMethod() {
        // 구현 코드
    }
}

 

아래는 인터페이스 Shape을 구현한 클래스 Circle의 예시이다.

interface Shape {
    double getArea();
    double getPerimeter();
}

class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getArea() {
        return Math.PI * radius * radius;
    }

    public double getPerimeter() {
        return 2 * Math.PI * radius;
    }
}

인터페이스 Shape은 getArea()와 getPerimeter() 메소드가 선언되어 있으며, 클래스 Circle은 이를 구현한다.

 

Circle 클래스는 Shape 인터페이스를 구현하기 위해 getArea()와 getPerimeter() 메소드를 정의해야 한다.

 

이제 Circle 객체는 Shape 인터페이스의 참조변수로 참조할 수 있게 되었다.

Shape circle = new Circle(2.0);
System.out.println(circle.getArea());
System.out.println(circle.getPerimeter());

 

출력 결과는 다음과 같이 나온다.

12.566370614359172
12.566370614359172
728x90
반응형

BELATED ARTICLES

more