1

While going through spring security modules I came across this piece of code inside the Principal Interface class. My understanding is that Interfaces do not implement anything concrete.

What is the reason for the below piece of code inside an Interface ?

public interface Principal {     
 //other method definitions

  public default boolean implies(Subject subject) {
    if (subject == null)
      return false;
    return subject.getPrincipals().contains(this);
  }
}
GhostCat
  • 137,827
  • 25
  • 176
  • 248
HopeKing
  • 3,317
  • 7
  • 39
  • 62

2 Answers2

4

Those are called default methods; and were introduced with Java8.

Quoting the Oracle tutorial:

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.

Meaning: starting with java8, we actually can add behavior into interfaces. The idea is to make it easier to enhance existing interfaces - not to provide a "generic" mixin/trait concept to Java.

In other words: according to the people behind Java, the main reason for default was the need to enhance a lot of existing collection interfaces to support the new stream paradigm.

It is also worth pointing out that Java8 interfaces also allow for static methods:

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.)

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

This is a default method for an interface, available since Java 8. It's a feature that allows developers to add new methods to an interface without breaking the existing implementations of these. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.

Refactoring an existing interface from a framework or even from the JDK is complicated. Modify one interface breaks all classes that extends the interface which means that adding any new method could break millions of lines of code. Therefore, default methods have introduced as a mechanism to extending interfaces in a backward compatible way.

Another potential usage would be to just call other methods from the interface like in a forEach option where you get a list parameter and call another method that accepts just one element.

My personal opinion is that default methods should be used as less as possible and to not contain any business logic. It's mainly made for keeping old interfaces (10+ years old) retro-compatible.

More details: https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html https://dzone.com/articles/interface-default-methods-java

mkbrv
  • 407
  • 4
  • 13