Programing

Java에서 기본 키워드의 목적은 무엇입니까?

lottogame 2020. 10. 15. 07:20
반응형

Java에서 기본 키워드의 목적은 무엇입니까?


Java의 인터페이스는 클래스와 비슷하지만 인터페이스 본문에는 추상 메서드final필드 (상수) 포함될 수 있습니다 .

최근에 다음과 같은 질문을 보았습니다.

interface AnInterface {
    public default void myMethod() {
        System.out.println("D");
    }
}

인터페이스 정의에 따라 추상 메서드 만 허용됩니다. 위 코드를 컴파일 할 수있는 이유는 무엇입니까? default키워드 는 무엇입니까 ?

반면에 아래 코드를 작성하려고 할 때 modifier default not allowed here

default class MyClass{

}

대신에

class MyClass {

}

누구든지 default키워드 의 목적을 말해 줄 수 있습니까 ? 인터페이스 내에서만 허용됩니까? default(액세스 수정 자 없음) 과 어떻게 다른 가요?


interface구현을 제공 할 수있는 Java 8의 새로운 기능입니다 . Java 8 JLS-13.5.6에 설명되어 있습니다. 읽는 인터페이스 메서드 선언 (일부)

default메서드를 추가 하거나 메서드를에서 abstract변경해도 default기존 바이너리와의 호환성이 깨지지는 않지만 IncompatibleClassChangeError기존 바이너리가 메서드를 호출하려고 시도하면이 ( 가) 발생할 수 있습니다 . 이 오류는 한정 유형 T이 두 인터페이스 I의 하위 유형 인 경우 발생합니다. J여기서 둘 다 I동일한 서명과 결과를 사용하여 메서드를 J선언하고 둘 다 선언 default하지 I않고 J다른 인터페이스의 하위 인터페이스 아닙니다 .

JDK 8의 새로운 기능에는 (일부)

기본 메서드를 사용하면 라이브러리 인터페이스에 새 기능을 추가 할 수 있으며 해당 인터페이스의 이전 버전 용으로 작성된 코드와 바이너리 호환성을 보장 할 수 있습니다.


기본 메서드는 주로 람다 식을 지원하기 위해 Java 8에 추가되었습니다. 디자이너는 (영리하게 생각하기에) 인터페이스의 익명 구현을 만들기 위해 람다 구문을 만들기로 결정했습니다. 그러나 주어진 람다는 단일 메소드 만 구현할 수 있으며, 이는 매우 심각한 제한이 될 단일 메소드가있는 인터페이스로 제한됩니다. 대신 더 복잡한 인터페이스를 사용할 수 있도록 기본 메서드가 추가되었습니다.

default람다로 인해 도입 된 주장에 대한 설득력이 필요한 경우 , 2009 년 Mark Reinhold가 작성한 Project Lambda 스트로 맨 제안 에는 람다를 지원하기 위해 추가해야 할 필수 기능으로 '확장 방법'이 언급되어 있습니다.

다음은 개념을 보여주는 예입니다.

interface Operator {
    int operate(int n);
    default int inverse(int n) {
        return -operate(n);
    }
}

public int applyInverse(int n, Operator operator) {
    return operator.inverse(n);
}

applyInverse(3, n -> n * n + 7);

나는 깨달았지만 default람다를 지원 하는 방법을 설명해야 합니다. inverse기본값 이기 때문에 필요한 경우 구현 클래스에서 쉽게 재정의 할 수 있습니다.


Java 8에는 기본 메소드라는 새로운 개념이 도입되었습니다. 기본 메서드는 기본 구현이 있으며 기존 코드를 손상시키지 않고 인터페이스를 발전시키는 데 도움이되는 메서드입니다. 예를 살펴 보겠습니다.

 public interface SimpleInterface {
    public void doSomeWork();

    //A default method in the interface created using "default" keyword

    default public void doSomeOtherWork(){

    System.out.println("DoSomeOtherWork implementation in the interface");
       }
    }

 class SimpleInterfaceImpl implements SimpleInterface{

  @Override
  public void doSomeWork() {
  System.out.println("Do Some Work implementation in the class");
   }

 /*
  * Not required to override to provide an implementation
  * for doSomeOtherWork.
  */

 public static void main(String[] args) {
   SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl();
   simpObj.doSomeWork();
   simpObj.doSomeOtherWork();
      }
   }

출력은 다음과 같습니다.


인터페이스의 DoSomeOtherWork 구현 클래스에서 Do Some Work 구현


다른 답변에서 간과되었던 것은 주석에서의 역할이었습니다. Java 1.5에서 default키워드는 주석 필드에 기본값제공하는 수단으로 사용 되었습니다.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Processor {
    String value() default "AMD";
}

인터페이스에서 기본 메소드를 정의 할 수 있도록 Java 8의 도입으로 사용량이 오버로드 되었습니다.

간과 된 또 다른 것 : 선언 default class MyClass {}이 유효하지 않은 이유 클래스가 전혀 선언 되는 방식 때문 입니다. 해당 키워드가 여기에 표시되도록 허용하는 언어 조항이 없습니다. 그러나 인터페이스 메서드 선언 에는 나타납니다 .


A very good explanation is found in The Java™ Tutorials, part of the explanation is as follows:

Consider an example that involves manufacturers of computer-controlled cars who publish industry-standard interfaces that describe which methods can be invoked to operate their cars. What if those computer-controlled car manufacturers add new functionality, such as flight, to their cars? These manufacturers would need to specify new methods to enable other companies (such as electronic guidance instrument manufacturers) to adapt their software to flying cars. Where would these car manufacturers declare these new flight-related methods? If they add them to their original interfaces, then programmers who have implemented those interfaces would have to rewrite their implementations. If they add them as static methods, then programmers would regard them as utility methods, not as essential, core methods.

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.


The new Java 8 feature (Default Methods) allows an interface to provide an implementation when its labeled with the default keyword.

For Example:

interface Test {
    default double getAvg(int avg) {
        return avg;
    }
}
class Tester implements Test{
 //compiles just fine
}

Interface Test uses the default keyword which allows the interface to provide a default implementation of the method without the need for implementing those methods in the classes that uses the interface.

Backward compatibility: Imagine that your interface is implemented by hundreds of classes, modifying that interface will force all the users to implement the newly added method, even though its not essential for many other classes that implements your interface.

Facts & Restrictions:

1-May only be declared within an interface and not within a class or abstract class.

2-Must provide a body

3-It is not assumed to be public or abstract as other normal methods used in an interface.


Default methods enable you to add new functionality to the interfaces of your apps. It can also be used to have a multi inheritance. In addition to default methods, you can define static methods in interfaces. This makes it easier for you to organize helper methods


Default methods in an interface allow us to add new functionality without breaking old code.

Before Java 8, if a new method was added to an interface, then all the implementation classes of that interface were bound to override that new method, even if they did not use the new functionality.

With Java 8, we can add the default implementation for the new method by using the default keyword before the method implementation.

Even with anonymous classes or functional interfaces, if we see that some code is reusable and we don’t want to define the same logic everywhere in the code, we can write default implementations of those and reuse them.

Example

public interface YourInterface {
    public void doSomeWork();

    //A default method in the interface created using "default" keyword
    default public void doSomeOtherWork(){

    System.out.println("DoSomeOtherWork implementation in the interface");
       }
    }

    class SimpleInterfaceImpl implements YourInterface{

     /*
     * Not required to override to provide an implementation
     * for doSomeOtherWork.
     */
      @Override
      public void doSomeWork() {
  System.out.println("Do Some Work implementation in the class");
   }

 /*
  * Main method
  */
 public static void main(String[] args) {
   SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl();
   simpObj.doSomeWork();
   simpObj.doSomeOtherWork();
      }
   }

참고URL : https://stackoverflow.com/questions/31578427/what-is-the-purpose-of-the-default-keyword-in-java

반응형