Nice programing

인터페이스 메서드에 본문이있을 수 있습니까?

nicepro 2020. 11. 14. 11:05
반응형

인터페이스 메서드에 본문이있을 수 있습니까?


인터페이스가 100 % 순수한 추상 클래스와 같다는 것을 알고 있습니다. 따라서 메서드 구현을 가질 수 없습니다. 하지만 이상한 코드를 보았습니다. 누구든지 설명 할 수 있습니까?

코드 스 니펫 :

 interface Whoa {
        public static void doStuff() {
            System.out.println("This is not default implementation");
        }
 }

편집하다:

내 IDE는 Intellij Idea 13.1입니다. 프로젝트 SDK는 java 7 <1.7.0_25>입니다. IDE에 컴파일러 오류가 표시되지 않습니다. 그러나 명령 줄에서 코드를 컴파일하면 다음 메시지가 표시됩니다.

Whoa.java:2: error: modifier static not allowed here
    public static void doStuff() {
                       ^

에서 자바 (8) 당신은 기본 방법 외에 인터페이스에 정적 메서드를 정의 할 수 있습니다.

  • 정적 메서드는 개체가 아닌 정의 된 클래스와 연결된 메서드입니다. 클래스의 모든 인스턴스는 정적 메서드를 공유합니다.

  • 이렇게하면 라이브러리에서 도우미 메서드를 쉽게 구성 할 수 있습니다. 인터페이스에 특정한 정적 메서드를 별도의 클래스가 아닌 동일한 인터페이스에 유지할 수 있습니다.

  • 다음 예제에서는 ZoneId표준 시간대 식별자에 해당 하는 개체 를 검색하는 정적 메서드를 정의합니다 . ZoneId주어진 식별자에 해당하는 개체 가 없으면 시스템 기본 시간대를 사용합니다 . (결과적으로 방법을 단순화 할 수 있습니다 getZonedDateTime)

다음은 코드입니다.

public interface TimeClient {
   // ...
    static public ZoneId getZoneId (String zoneString) {
        try {
            return ZoneId.of(zoneString);
        } catch (DateTimeException e) {
            System.err.println("Invalid time zone: " + zoneString +"; using default time zone instead.");
            return ZoneId.systemDefault();
        }
    }

   default public ZonedDateTime getZonedDateTime(String zoneString) {
      return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
   }    
}

또한보십시오


이는 Java 8에서만 가능합니다. Java 7 언어 사양 §9.4 에서 다음과 같이 명시 적으로 설명합니다.

인터페이스에서 선언 된 메서드가 정적으로 선언되면 컴파일 타임 오류입니다. 정적 메서드는 추상이 될 수 없기 때문입니다.

따라서 Java 7에서는 인터페이스의 정적 메서드가 존재할 수 없습니다 .

Java 8 언어 사양 §9.4.3으로 이동하면 다음과 같은 내용을 볼 수 있습니다.

정적 메서드에는 메서드 구현을 제공하는 블록 본문도 있습니다.

따라서 Java 8에서는 존재할 있다고 명시 적으로 설명 합니다.

Java 1.7.0_45에서 정확한 코드를 실행하려고 시도했지만 "정적 수정자가 허용되지 않습니다"라는 오류가 발생했습니다.


다음은 Java 8 자습서 인 Default Methods (Java 언어 학습> 인터페이스 및 상속) 에서 직접 인용 한 것입니다 .

정적 방법

In addition to default methods, you can define static methods in interfaces. (A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.) This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class. The following example defines a static method that retrieves a ZoneId object corresponding to a time zone identifier; it uses the system default time zone if there is no ZoneId object corresponding to the given identifier. (As a result, you can simplify the method getZonedDateTime):

public interface TimeClient {
    // ...
    static public ZoneId getZoneId (String zoneString) {
        try {
            return ZoneId.of(zoneString);
        } catch (DateTimeException e) {
            System.err.println("Invalid time zone: " + zoneString +
                "; using default time zone instead.");
            return ZoneId.systemDefault();
        }
    }

    default public ZonedDateTime getZonedDateTime(String zoneString) {
        return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
    }    
}

Like static methods in classes, you specify that a method definition in an interface is a static method with the static keyword at the beginning of the method signature. All method declarations in an interface, including static methods, are implicitly public, so you can omit the public modifier.


For java version 7 or below, similar functionally you can achieve using nested class declared within interface body. and this nested class implements outer interface.

Example:

interface I1{
    public void doSmth();

    class DefaultRealizationClass implements  I1{

        @Override
        public void doSmth() {
           System.out.println("default realization");
        }
    }
}

How do we use it in our code?

class MyClass implements I1{

    @Override
    public void doSmth() {
         new I1.DefaultRealizationClass().doSmth();
    }   
}

Therefore default implementation encapsulated within interface.

참고URL : https://stackoverflow.com/questions/22713652/can-an-interface-method-have-a-body

반응형