3

Why interfaces cannot be declared as static ?

4 Answers 4

6

Think of an interface like a blueprint. it's nothing concrete. Just a blueprint of what a class must implement if adheres (inherits) the interface.

Java (iirc) doesn't have a concept of "static" classes per se, that is "Static" isn't a keyword on the class declaration like it is in C#. Instead a static class is a class that is only made up of static members and methods.

As you may know, static members and static methods belong to the class, and not the instance.

Since an interface is just a blueprint and not concrete, a "static" interface is meaningless.

The one caveat to this is inner classes.

In a class declaration, you can define an interface that is static, but I assume it does nothing.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Good explanation. But what do you mean by "I assume it does nothing"?
2

First, because it won't make sense. How a static interface would be different from a non-static interface?

Second, they can:

public class SomeClass {
    static interface StaticInterface {
    }
}

Comments

2

If you mean the interface itself: Because there isn't really anything useful you could mean with static interface

If you mean interface methods: Because in Java, static methods are a property of a class and cannot be overridden or invoked polymorphically.

Comments

0

Actualy, I see some sense in interfaces which cannot be implemented (especially before enums were introduced in Java 5):

public static (or better final?) interface Colors {
   public final int RED = 1;
   public final int GREEN = 2;
   ...
}

If someone knows why these things shouldn't be done in this way (assume we're still in java_1.4), please, leave comments.

5 Comments

I think interfaces are more about behaviour and not about data. If there are no enums I would move this (static) data to a class.
That's the "Constant Interface Anti-Pattern".
This is actually called the constant interface antipattern (see Wikipedia for reference). The alternative is to use a concrete class (private constructor).
@Willi Schönborn, @Helper Method: in my answer the main point is that why there were no possibility to restrict implement certain interface (like final class). This restriction would negate main problems described in wikipedia article (and as you can see they suggest as an alternative to use final class without methods and with private constructor - actually the same solution).
Sorry, i don't get the use case. What do you mean?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.