Skip to content
Advertisement

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

I ran into the following code recently:

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

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

Advertisement

Answer

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.

Advertisement