자바(Java)에서 인터페이스(interface)는 클래스와 비슷하지만, 추상 메서드와 static이며 final인 필드만 가질 수 있다는 점이 다릅니다. 그리고 클래스를 상속하듯이 extends 키워드를 사용하면 한 인터페이스가 다른 인터페이스를 확장할 수 있습니다.
interface ArithmeticCalculations {
public abstract int addition(int a, int b);
public abstract int subtraction(int a, int b);
}
interface MathCalculations extends ArithmeticCalculations {
public abstract double squareRoot(int a);
public abstract double powerOf(int a, int b);
}여러 인터페이스를 동시에 확장하기
같은 방식으로 extends 키워드 뒤에 쉼표(,)로 구분하여 여러 인터페이스를 나열하면, 하나의 인터페이스가 여러 인터페이스를 동시에 확장할 수 있습니다.
interface MyInterface extends ArithmeticCalculations, MathCalculations {예제
다음 자바 프로그램은 하나의 인터페이스가 두 개의 인터페이스를 동시에 확장하고, 해당 인터페이스를 구현하는 클래스가 모든 추상 메서드를 어떻게 구현하는지 보여줍니다.
import java.util.Scanner;
interface ArithmeticCalculations {
public abstract int addition(int a, int b);
public abstract int subtraction(int a, int b);
}
interface MathCalculations {
public abstract double squareRoot(int a);
public abstract double powerOf(int a, int b);
}
interface MyInterface extends MathCalculations, ArithmeticCalculations {
public void displayResults();
}
public class ExtendingInterfaceExample implements MyInterface {
public int addition(int a, int b) {
return a+b;
}
public int subtraction(int a, int b) {
return a-b;
}
public double squareRoot(int a) {
return Math.sqrt(a);
}
public double powerOf(int a, int b) {
return Math.pow(a, b);
}
public void displayResults() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of a: ");
int a = sc.nextInt();
System.out.println("Enter the value of b: ");
int b = sc.nextInt();
ExtendingInterfaceExample obj = new ExtendingInterfaceExample();
System.out.println("Result of addition: "+obj.addition(a, b));
System.out.println("Result of subtraction: "+obj.subtraction(a, b));
System.out.println("Square root of "+a+" is: "+obj.squareRoot(a));
System.out.println(a+"^"+b+" value is: "+obj.powerOf(a, b));
}
public static void main(String args[]) {
new ExtendingInterfaceExample().displayResults();
}
}실행 결과
Enter the value of a: 4 Enter the value of b: 3 Result of addition: 7 Result of subtraction: 1 Square root of 4 is: 2.0 4^3 value is: 64.0
핵심 정리
- 클래스는 단 하나의 클래스만 상속할 수 있지만, 인터페이스는
extends키워드와 쉼표(,)를 이용해 여러 인터페이스를 동시에 확장할 수 있습니다. - 확장된 인터페이스의 모든 추상 메서드는 최종 구현 클래스에서 반드시 구현해야 하며, 그렇지 않으면 컴파일 오류가 발생합니다.
- Java 8부터는 인터페이스에
default메서드와static메서드도 포함할 수 있어, 다중 상속과 유사한 기능을 더욱 유연하게 활용할 수 있습니다.