开发者

Java - Interfaces

开发者 https://www.devze.com 2022-12-23 21:00 出处:网络
Why开发者_StackOverflow中文版 interfaces cannot be declared as static ?Think of an interface like a blueprint. it\'s nothing concrete. Just a blueprint of what a class must implement if adheres (inher

Why开发者_StackOverflow中文版 interfaces cannot be declared as static ?


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.


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 {
    }
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号