Java – Does an Interface really have no state or behavior

interfacesjava

going through the web I always read something like

Java Interfaces have no state and no behavior

If you look what the common definition of state is then you likely end with

what the objects have, Student have a first name, last name, age, etc

The thing is I guess since Java 8 with their default methods I can also define some fields and use them as well as functions.

So I wonder if it's still valid to say that an interface in Java has no state and no behavior?

public interface DefaultInterface {

    List<Integer> numbers = new LinkedList<>();

    default List<Integer> getNumbers() {
        return numbers;
    }

    default void addId(int value) {
        numbers.add(value);
    }

    default IntStream perform(String string) {
        return string.chars();
    }

    void implementMe();
}

Best Answer

For a long time, Java interfaces could only be "pure" interfaces without default implementation, state, behavior. Default interface implementation is a fairly recent language feature. It appeared in Java 8 (2014).

The intent behind interfaces with default implementation was to allow adding methods to an interface without having to change the existing classes which implement that interface. The new methods get default implementations (while the old methods likely remain without default implementations), and the existing classes which implement the interface don't have to implement new methods.

Interfaces with default implementation could also be used like abstract classes for multiple [implementation] inheritance.

Let's look at interfaces in other languages.

  • C++ doesn't have a special interface keyword. Pure interfaces (without a default implementation) are declared with class keyword and pure virtual functions.

  • C# does have a special interface keyword, but no default implementation for interfaces. So, a type declared with interface can be only a pure interface without implementation.

Related Topic