Skip to content

Latest commit

 

History

History
83 lines (72 loc) · 2.67 KB

define_and_write_functional_interfaces.md

File metadata and controls

83 lines (72 loc) · 2.67 KB

Define and write functional interfaces

Functional Interfaces

Each functional interface has a single abstract method called the functional method for that functional interface. You can supply a lambda expression whenever an object of an interface with a single abstract method is expected.

public interface Predicate<T> {
  boolean test(T t);
}

@FunctionalInterface annotation

The @FunctionalInterface annotation was introduced to communicate that an interface was intended as a functional interface Its use is optional. It only serves as a hint to the compiler

Code Sample

Default methods in interfaces

As functional interfaces require a single abstract method, the following code will not compile

@FunctionalInterface
public interface IFoo {
  default void actionFoo(){
    //some action code here
  }
}

but this code will compile

@FunctionalInterface
public interface IFoo {
  default void actionFoo(){
    //some action code here
  }
  boolean isFooAllowed(); //single abstract method
}

Code Sample

Static methods in interfaces

The same applies the static methods as was outlined in the default methods section. The following code will not compile

@FunctionalInterface
public interface IFoo {
  static void actionFoo(){
    //some action code here
  }
}

but this code will compile

@FunctionalInterface
public interface IFoo {
  static void actionFoo(){
    //some action code here
  }
  boolean isFooAllowed(); //single abstract method
}

Code Sample

Public methods of java.lang.Object in functional interfaces

If an interface declares an abstract method overriding one of the public methods of java.lang.Object, it doe not count toward the interface's abstract method count. This is because any implementation of the interface will have an implementation from java.lang.Object or elsewhere

@FunctionalInterface
public interface IFoo {
  static void actionFoo(){
    //some action code here
  }
  boolean isFooAllowed(); //single abstract method
  
  boolean equals(Object var1); // ignored as its a public method from java.lang.Object
}

Code Sample

Previous Next