Nelly
Nelly

Reputation: 309

Java functional interface

I am new to Java8 and I read a couple of things about this topic on the Internet. For the moment I am trying to figure out what functional interfaces are. I've found some examples, but I do not understand why the interface Skip is a functional one, since it has 2 defined methods. I hope that someone can explain me a bit. The code is:

 @FunctionalInterface
 public interface Sprint 
 {
     public void sprint(Animal animal);
 }


 @FunctionalInterface
 public interface Skip extends Sprint 
 {

      public default int getHopCount() 
      {
         return 10;
      }

      public static void skip(int speed) {}
 }

Upvotes: 0

Views: 647

Answers (2)

bcsb1001
bcsb1001

Reputation: 2907

The best way to think about it is: would it make sense to express an instance of this interface as a single lambda? This is true when there is exactly one abstract method in your interface.

Sprint has the method sprint(), which is abstract. A lambda for this interface would look something like:

Sprint sprint = animal -> {
    animal.doThingOne();
    animal.doThingTwo();
}

Skip has a static method and a default method. static methods aren't anything to do with instances; this is the meaning of static in Java. Additionally, default methods don't have to be implemented in subclasses as a default implementation is already provided. This means that a lambda only has to implement the abstract method in Skip (sprint() again, inherited from Sprint) to be valid. Example:

Skip skip = Animal::doThingThree; // Equivalent to: animal -> animal.doThingThree()

As static and default methods don't have to be implemented by a lambda, you can have as many as you want and still have a functional interface.

Upvotes: 2

Eran
Eran

Reputation: 393771

Your Skip interface has only one abstract method (default and static methods don't count) - the sprint method inherited from the Sprint interface. Therefore it is a functional interface.

Upvotes: 5

Related Questions