[Java] 다중 인터페이스 상속에서의 메소드 중복은 어떻게 동작할까

인터페이스들의 메소드 중복

인터페이스들간의 메소드가 중복될 경우 어떻게 처리 될지가 궁금하여 테스트해 보았다. 우선적으로 default가 아닌 인터페이스 메소드는 제외했다. default가 아니라면 상속을 받은 뒤에 구현을 해야함은 변함이 없기 때문이다.

case1.

하나는 default 메소드이고 하나는 virtual 메소드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface SomeInterface1 {
default void someMethod() {
System.out.println("Interface1 Method");
}
}

public interface SomeInterface2 {
void someMethod();
}

public class SomeClass implements SomeInterface1, SomeInterface2{

}

SomeInterface2의 메소드를 구현하라는 경고가 표시된다.

case2.

둘 다 default 메소드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface SomeInterface1 {
default void someMethod() {
System.out.println("Interface1 Method");
}
}

public interface SomeInterface2 {
default void someMethod() {
System.out.println("Interface2 Method");
}
}

public class SomeClass implements SomeInterface1, SomeInterface2{

}

conflict 경고가 표시된다.

case3.

인터페이스가 상속관계에 존재하고 상위 인터페이스는 default이고 하위 인터페이스는 virtual이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface SomeInterface1 {
default void someMethod() {
System.out.println("Interface1 Method");
}
}

public interface SomeInheritanceInterface extends SomeInterface1 {
void someMethod();
}

public class SomeClass implements SomeInheritanceInterface{

}

SomeInheritanceInterface의 메소드를 구현하라는 경고가 표시된다.

case4.

인터페이스가 상속관계에 존재하고 모두 default 메소드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public interface SomeInterface1 {
default void someMethod() {
System.out.println("Interface1 Method");
}
}

public interface SomeInheritanceInterface extends SomeInterface1 {
default void someMethod() {
System.out.println("SomeInheritanceInterface Method");
}
}

public class SomeClass implements SomeInheritanceInterface{

}

오버라이드 되었기 때문에 하위 인터페이스의 default 메소드가 수행된다.

다중 확장에서 명시적 인터페이스 메소드 호출

case2와 같은 경우에서 두 인터페이스의 default 메소드를 호출하고 싶다면 다음과 같이 수행하면 된다.

1
2
3
4
5
6
7
public class SomeClass implements SomeInterface1, SomeInterface2{
@Override
public void someMethod() {
SomeInterface1.super.someMethod();
SomeInterface2.super.someMethod();
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/08/11/Languages/Java/duplicateMethodInterface/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.