Why would you declare a variable of type X within the interface X in Java?

Tags: , ,

I ran into the following code recently:

public interface Filter {
      Filter NULL_FILTER = new Filter() {
            public Query getFilterCriteria() {
              return null;
            public void setArrayClause(ArrayClause arrayClause) {}
      /** @return Filter criteria or null if not set */
      Query getFilterCriteria();
  default Filter withProjection(Set<Field> projection) {
    return this;

It is confusing to me what the purpose of this could be. Can someone explain why someone would write this code?


Every field in an interface is implicitly static, so this isn’t defining something that lives in every Filter — it’s defining one common Filter that is stored in the Filter interface’s namespace, so you can just write

Filter defaultFilter = Filter.NULL_FILTER;

Nothing more complicated than that. It’s not uncommon to have factory methods or constant values of an interface defined in that interface — e.g. Comparator.naturalOrder() in Java 8.

Source: stackoverflow