Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 897
Nitin T Avatar asked Feb 23 '20 06:02

Nitin T


People also ask

Can functional interface have multiple methods?

An Interface that contains exactly one abstract method is known as functional interface. It can have any number of default, static methods but can contain only one abstract method. It can also declare methods of object class.

Can functional interface have multiple static methods?

Functional interface can have only one abstract method. It can contain multiple default and static methods.

Why do functional interface have only one method?

Important : The functional interface also known as Single Abstract Method Interface was introduced to facilitate Lambda functions. Since a lambda function can only provide the implementation for 1 method it is mandatory for the functional interface to have ONLY one abstract method.

How many default methods can a functional interface have?

Conceptually, a functional interface has exactly one abstract method.


1 Answers

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
like image 117
kriegaex Avatar answered Oct 01 '22 01:10

kriegaex