Java에서 인터페이스(Interface)는 클래스와 유사한 참조 타입이지만, 오직 추상 메서드와 final이면서 static인 필드(상수)만 포함할 수 있다는 점이 다릅니다.
extends 키워드로 여러 인터페이스 상속하기
클래스와 마찬가지로 extends 키워드를 사용하면 한 인터페이스가 다른 인터페이스를 확장(상속)할 수 있습니다. 특히 Java의 인터페이스는 클래스와 달리 다중 상속이 가능하며, extends 키워드 뒤에 쉼표(,)로 구분하여 여러 인터페이스를 동시에 상속받을 수 있습니다.
interface MyInterface extends ArithmeticCalculations, MathCalculations {위 코드에서 MyInterface는 ArithmeticCalculations와 MathCalculations 두 인터페이스를 모두 상속받습니다. 이렇게 하면 하위 인터페이스를 구현하는 클래스는 부모 인터페이스들의 모든 추상 메서드를 구현해야 합니다.
예제 코드
다음은 하나의 인터페이스가 여러 인터페이스를 상속하는 방법을 보여주는 Java 프로그램입니다.
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();
}
}코드 설명
ArithmeticCalculations인터페이스는 덧셈과 뺄셈 메서드를 선언합니다.MathCalculations인터페이스는 제곱근과 거듭제곱 메서드를 선언합니다.MyInterface는 위 두 인터페이스를 동시에 상속하고, 추가로displayResults()메서드를 선언합니다.ExtendingInterfaceExample클래스는MyInterface를 구현하므로, 상속된 모든 추상 메서드를 반드시 구현해야 합니다.
실행 결과
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
정리
Java에서 인터페이스는 extends 키워드와 쉼표를 활용해 여러 인터페이스를 동시에 상속할 수 있습니다. 이는 Java가 클래스의 다중 상속은 지원하지 않지만, 인터페이스를 통해서는 다중 상속과 유사한 효과를 얻을 수 있음을 보여주는 대표적인 예입니다.