java – What is a static interface used for?

Question:

The sample snippet defines a static interface to notify the activity about clicks:

static interface WorkoutListListener {
    void itemClicked(long id);
};

Why is the interface static? For example, if a variable is static, it is used in a single instance for all instances of the class, but what do static interfaces do?

Answer:

According to JLS 8.5.1. Static Member Type Declarations :

A member interface is implicitly static ( §9.1.1 ). It is permitted for the declaration of a member interface to redundantly specify the static modifier.


The interface is a member of the class and is implicitly static. When declaring a class member interface, an excessive indication of the static modifier is allowed.

Constructions

public class SomeClass {
    abstract static interface Interface {
        public abstract void foo();
    }
}

and

public class SomeClass {
    interface Interface {
        void foo();
    }
}

are equivalent since the interface is always abstract , the nested interface is always static , and the interface methods are always public . Before java 8, interface methods were always abstract , in the eighth version, the interface method can be static or default , in the absence of these modifiers abstract implied. Explicit specification of modifiers is acceptable, but not encouraged from a style point of view.

Fields in the interface are always public , static and final , redundant indication of these modifiers is also permissible.

Scroll to Top