Why is there no compile error for my @FunctionalInterface with two methods?

Nitin T :

Is below interface a valid functional interface in Java 8?

@FunctionalInterface
interface Normal{
    public abstract String move();
    public abstract String toString() ;
}

Why doesn't it give me a compile time error?

kriegaex :

What Alok quoted is true, but he overlooked something, which makes his final answer (that the code is invalid) wrong:

The interface has one method String toString() which every class already implements, inheriting it from Object. I.e. the declared interface method already has an implementation, similar to a default method. Hence, there is no compile error and Normal can be used as a functional interface as shown in my MCVE:

package de.scrum_master.stackoverflow;

@FunctionalInterface
interface Normal {
  String move();
  String toString();
}

BTW, no need to declare interface methods as public because they always are. Same goes for abstract.

package de.scrum_master.stackoverflow;

public class NormalApp {
  static void doSomething(Normal normal) {
    System.out.println(normal.move());
    System.out.println(normal.toString());
  }

  public static void main(String[] args) {
    doSomething(() -> "xxx");
  }
}

If you run the driver application, you will see this console log:

xxx
de.scrum_master.stackoverflow.NormalApp$$Lambda$1/1530388690@28c97a5

Now if you change the method name toString to something else, e.g. toStringX, you will see that due to the @FunctionalInterface there is the expected error message when compiling the class:

Unexpected @FunctionalInterface annotation
  de.scrum_master.stackoverflow.Normal is not a functional interface
    multiple non-overriding abstract methods found in interface de.scrum_master.stackoverflow.Normal

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=3542&siteId=1