Java 8에서 추상 클래스와 인터페이스의 차이점은 무엇입니까?
자바에서는 추상 클래스와 인터페이스 사이에 미묘하지만 중요한 차이점이 있었습니다. 기본 구현 입니다. 추상 클래스는 그것들을 가질 수 있지만 인터페이스는 가질 수 없습니다. 그러나 Java 8은 인터페이스에 대한 기본 구현을 도입하므로 더 이상 인터페이스와 추상 클래스 간의 중요한 차이가 아닙니다.
그래서 무엇입니까?
내가 말할 수있는 한, 유일한 차이점은 (아마도 후드 효율성에 대한 일부를 제외하고) 추상 클래스는 전통적인 Java 단일 상속을 따르는 반면 인터페이스는 다중 상속 (또는 원하는 경우 다중 구현)을 가질 수 있다는 것입니다. 이것은 나를 다른 질문으로 인도합니다.
새로운 Java 8 인터페이스는 다이아몬드 문제를 어떻게 피 합니까?
인터페이스는 연관된 상태를 가질 수 없습니다.
추상 클래스는 그들과 관련된 상태를 가질 수 있습니다.
또한 인터페이스의 기본 메서드를 구현할 필요가 없습니다. 따라서 인터페이스가 업데이트를받는 동안 구현 클래스가이를 구현할 필요가 없기 때문에 이러한 방식으로 기존 코드가 손상되지 않습니다.
결과적으로 차선의 코드를 얻을 수 있지만 더 최적의 코드를 원한다면 기본 구현을 재정의하는 것이 좋습니다.
다이아몬드 문제가 발생할 경우 그리고 마지막으로, 다음, 컴파일러는 경고합니다, 그리고 당신은 당신이 구현하고자하는 인터페이스를 선택해야합니다.
다이아몬드 문제에 대한 자세한 내용을 보려면 다음 코드를 고려하십시오.
interface A {
void method();
}
interface B extends A {
@Override
default void method() {
System.out.println("B");
}
}
interface C extends A {
@Override
default void method() {
System.out.println("C");
}
}
interface D extends B, C {
}
여기에 컴파일러 오류가 발생 interface D extends B, C
합니다.
interface D inherits unrelated defaults for method() form types B and C
수정 사항은 다음과 같습니다.
interface D extends B, C {
@Override
default void method() {
B.super.method();
}
}
경우에 나는을 상속 원 method()
에서 B
.
if D
가 class
.
Java 8에서 인터페이스와 추상 클래스의 차이점에 대해 더 자세히 알아 보려면 다음을 고려하십시오 Team
.
interface Player {
}
interface Team {
void addPlayer(Player player);
}
이론적으로는 addPlayer
플레이어 목록에 플레이어를 추가 할 수 있도록 기본 구현을 제공 할 수 있습니다.
하지만 기다려...?
플레이어 목록을 어떻게 저장합니까?
대답은 기본 구현을 사용할 수 있더라도 인터페이스에서이를 수행 할 수 없다는 것입니다.
이 매우 상세하게 답변하고, 그러나 내가 적어도 추상 클래스를 가지고있는 거의 정당화의 하나로서 고려하는 것이 한 점없는 것 같습니다 한 전혀를 :
추상 클래스는 보호 된 멤버 (및 기본 가시성을 가진 멤버) 를 가질 수 있습니다 . 인터페이스의 메서드는 암시 적으로 공개 됩니다.
다이아몬드 문제 의 정의 는 모호합니다. 다중 상속에서 발생할 수있는 모든 종류의 문제가 있습니다. 다행히도 대부분은 컴파일 타임에 쉽게 감지 할 수 있으며 프로그래밍 언어는 이러한 문제를 해결하기위한 간단한 솔루션을 지원합니다. 이러한 문제의 대부분은 다이아몬드 문제 에만 국한되지 않습니다 . 예를 들어, 다이아몬드 없이도 메서드 정의가 충돌 할 수 있습니다 .
interface Bar {
default int test() { return 42; }
}
interface Baz {
default int test() { return 6 * 9; }
}
class Foo implements Bar, Baz { }
The specific problem with diamonds is the question of inclusive vs. exclusive. If you have a type hierarchy where B and C derive from A, and D derives from B and C, then the question is:
- is D a B *and* a C (i.e. one type of A), or
- is D a B *or* a C (i.e. two types of A).
Well, in Java 8 the type A has to be an interface. So it makes no difference, because interfaces have no state. It doesn't matter, that interfaces can define default methods, since they also have no state. They can invoke methods that have direct access to state. However, these methods are always implemented based on single inheritance.
Now that interfaces can contain executable code, lots of use-cases for abstract classes are taken over by interfaces. But abstract classes can still have member variables, while interfaces can't.
The diamond problem is avoided by simply not allowing a class to implement two interfaces when both interfaces provide a default implementation for the same method with the same signature.
Java 8 though introduces default implementations for interfaces, meaning this is no longer the critical difference between an interface and an abstract class.
Still there are few more critical differences. Refer to this post:
Interface with default methods vs Abstract class in Java 8
How do the new Java 8 interfaces avoid the diamond Problem?
Case 1: You are implementing two interfaces, which have same default
method, you have to resolve the conflict in your implementation class
interface interfaceA{
default public void foo(){
System.out.println("InterfaceA foo");
}
}
interface interfaceB{
default public void foo(){
System.out.println("InterfaceB foo");
}
}
public class DiamondExample implements interfaceA,interfaceB{
public void foo(){
interfaceA.super.foo();
}
public static void main(String args[]){
new DiamondExample().foo();
}
}
Above example produce below outout:
InterfaceA foo
Case 2: You are extending a base class and implementing an interface with default method. Compiler resolves the diamond problem for you and you don't have to resolve it as in first example.
interface interfaceA{
default public void foo(){
System.out.println("InterfaceA foo");
}
}
class DiamondBase {
public void foo(){
System.out.println("Diamond base foo");
}
}
public class DiamondExample extends DiamondBase implements interfaceA{
public static void main(String args[]){
new DiamondExample().foo();
}
}
Above example produce below output:
Diamond base foo
'Nice programing' 카테고리의 다른 글
C ++에서 생성자의 실패를 처리하는 방법은 무엇입니까? (0) | 2020.11.21 |
---|---|
java.lang.IndexOutOfBoundsException : 소스가 대상에 맞지 않습니다. (0) | 2020.11.21 |
프로그래밍 방식으로 이미지를 만화 화하는 방법은 무엇입니까? (0) | 2020.11.21 |
CSS로 플로트 탑을 어떻게 만들 수 있습니까? (0) | 2020.11.21 |
XMPP의 "명단"은 무엇입니까? (0) | 2020.11.21 |