JDK 8의 기본값은 Java의 다중 상속 형태입니까?
JDK 8의 새로운 기능을 사용하면 바이너리 호환성을 유지하면서 기존 인터페이스에 추가 할 수 있습니다.
구문은 다음과 같습니다.
public interface SomeInterface() {
void existingInterface();
void newInterface() default SomeClass.defaultImplementation;
}
이렇게하면 기존의 모든 구현 SomeInterface에서이 새 버전으로 업그레이드 할 때 갑자기 newInterface().
이것은 깔끔하지만 구현하지 않은 새 기본 메서드를 추가 한 두 개의 인터페이스를 구현할 때 어떤 일이 발생합니까? 예를 들어 설명하겠습니다.
public interface Attendance {
boolean present() default DefaultAttendance.present;
}
public interface Timeline {
boolean present() default DefaultTimeline.present;
}
public class TimeTravelingStudent implements Attendance, Timeline {
}
// which code gets called?
new TimeTravelingStudent().present();
아직 JDK 8의 일부로 정의 되었습니까?
나는 http://cs.oswego.edu/pipermail/lambda-lib/2011-February/000068.html 에서 비슷한 것에 대해 이야기하고있는 자바 신들을 찾았 지만, 그것의 일부는 개인 메일 링리스트의 일부이며 직접 물어볼 수는 없습니다.
JDK 8에서 기본값을 사용하는 방법과 람다를 지원하도록 Collection 인터페이스를 확장하는 방법에 대한 자세한 내용은 https://oracleus.wingateweb.com/published/oracleus2011/sessions/25066/25066_Cho223662.pdf를 참조하십시오.
시청할 비디오 세션은 여기에 있습니다. http://medianetwork.oracle.com/video/player/1113272518001 이것은 디자이너가 Virtual Extensions라는 기능에 대해 이야기하고 있습니다. 그는 또한 이것이 이전 버전과의 호환성을 깨지 않는 방법에 대해서도 이야기합니다.
복제 작업에 대한 대답은 다음과 같습니다.
다중 상속 문제를 해결하려면 동일한 메서드 이름과 서명에 대한 기본 구현을 제공하는 두 인터페이스를 구현하는 클래스가 메서드 구현을 제공해야합니다. [전체 기사]
귀하의 질문에 대한 제 대답은 다음과 같습니다. 예, 여러 부모로부터 행동을 상속받을 수 있기 때문에 다중 상속의 한 형태입니다. 빠진 것은 상태, 즉 속성을 상속하는 것입니다.
나는 이것이 오래된 게시물이라는 것을 알고 있지만, 나는이 일을하고 있기 때문에 ...
컴파일러에서 다음과 같은 오류가 발생합니다.
 TimeTravelingStudent 클래스는 출석 유형에서 present ()에 대한 관련없는 기본값을 상속하고 현재에 대한 타임 라인 참조가 모호합니다. 둘 다 Timeline의 present () 메서드와 Attendance match의 present () 메서드가 있습니다.
거기 두 시나리오 :
1) 먼저 언급했는데, 가장 구체적인 인터페이스 가 없는 경우
public interface A {
default void doStuff(){ /* implementation */ }
}
public interface B {
default void doStuff() { /* implementation */ }
}
public class C implements A, B {
// option 1: own implementation
// OR
// option 2: use new syntax to call specific interface or face compilation error
void doStuff(){
B.super.doStuff();
}
}
2) 둘째, 보다 구체적인 인터페이스가있는 경우 :
public interface A {
default void doStuff() { /* implementation */ }
}
public interface B extends A {
default void doStuff() { /* implementation */ }
}
public class C implements A, B {
// will use method from B, as it is "closer" to C
}
귀하의 질문에 대한 제 대답은 다음과 같습니다. 예, 여러 부모로부터 행동을 상속받을 수 있기 때문에 다중 상속의 한 형태입니다. 빠진 것은 상태, 즉 속성을 상속하는 것입니다.
Yes, but you can add getters and setters to your interface that the implementing classes then must implement. Nevertheless, the implementing classes don't inherit attributes. So, AFAICS, it's more like a trait-style solution rather than a multiple inheritance style solution.
In short: it's a compile time error, must override the method by hand in the implementation.
Purpose of default method
The major purpose to introduce default method in Java 8, is to make interface extendable, without breaking existing implementations (there are so many 3rd party Java libraries).
And multiple inheritance like in C++ is actually intended to be avoided, that's definitely not the purpose of default method in Java.
How to override
2 options:
- Override the method, with its own logic.
- Override the method, call one of the interface's method via
super, format:<interface_name>.super.<method_name>();
Tips:
- method from interface is default to public, so don't forget to add
publickeyword when override it.
If anyone's still looking for an answer, in case a class implements two interfaces with the same default method then the class needs to resolve the disambiguity by providing an implementation of its own. Look at this tutorial for more details on how inheritance in default methods work.
"How will we distinguish the methods" was a question that was put on Stackoverflow and referred to this question concrete methods in interfaces Java1.8
The following is an example that should answer that question:
interface A{
default public void m(){
System.out.println("Interface A: m()");
}
}
interface B{
default public void m(){
System.out.println("Interface B: m()");
}
}
class C implements A,B {
public void m(){
System.out.println("Concrete C: m()");
}
public static void main(String[] args) {
C aC = new C();
aC.m();
new A(){}.m();
new B(){}.m();
}
}
Class C above must implement its own concrete method of the interfaces A and B. Namely:
public void m(){
System.out.println("Interface C: m()");
}
To call a concrete implementation of a method from a specific interface, you can instantiate the interface and explicitly call the concrete method of that interface
For example, the following code calls the concrete implementation of the method m() from interface A:
new A(){}.m();
The output of the above would be:
Interface A: m()
As far as I see it, it is no multiple inheritance because they are stateless. So virtual extension methods don't support full object or class functionality.
'Program Club' 카테고리의 다른 글
| C ++ 용 LINQ 라이브러리가 있습니까? (0) | 2020.10.12 |
|---|---|
| Common Lisp를 실제로 사용하는 방법을 배울 수있는 곳 (0) | 2020.10.12 |
| Gradle 기반 구성을 사용할 때 Android Studio (IntelliJ)에서 간단한 JUnit 테스트 실행 (0) | 2020.10.12 |
| HTML5 기록 popstate에서 브라우저 스크롤 방지 (0) | 2020.10.12 |
| 변수를 사용하여 ggplot에서 열 이름을 지정하는 방법 (0) | 2020.10.11 |