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:

JavaScript

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

JavaScript

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