开发者

Why do some developers declare String objects in their Interfaces in Java, and how does it work?

When I was analysing a code in my project, I came accross this situation. I have got an Interface with complete String consta开发者_运维问答nts declaration as below

public interface SampleInterface {
    String EXAMPLE_ONE = "exampleOne";
    String USER_ID     = "userId";

    public void setValue();
}

If any class implements this SampleInterface interface, what happens to the variables it declares?

  • Does the inherited class get access to all the variables?
  • Does the implemented class needs to override the declarations?
  • What might be the purpose of declaring the String variables in an interface, when we could use an abstract class for this purpose?

Also, what is the best strategy:

  1. A class with the final static fields and a private constructor?
  2. An Interface with the variables as seen above?


It's a Common Java Idiom

In an interface in Java, all members are implicitly public, and fields in particular are implicitly public static final. You DON'T have a choice. If you try to use any other permission level than public, the compiler would scream at you as it wouldn't make any sense.

So any implementing class will indeed inherit the members, including these static constant fields.

Why do People Use this Idiom?

There are several reasons why you would do this in an interface, and usually it is to use it as a constant store. This idiom is used to simply bundle constants together in one place, not necessarily to have the interface used as part of an inheritance tree in an OO way.

So you can call as usuall MyInterface.MY_CONST to access one of your constants.

You would do this over an interface usually when you don't need any behavior to be defined, so when you don't need any methods. It's really just a static store (often, the interface is made final itself as well). You could use an abstract class for this as well, for instance if you want to encapsulate and hide details of an implementation. But in this case, where you have both fields and methods, usually your objective is simply to provide some constants and a contract for sub-classes.

Considering in your case there's also a method signature as part of your interface, there's obviously an intent to implement this interface. In which case you can still access your data as either:

  • MyInterface.MY_CONST,
  • or MyExtendingClass.MY_CONST,
  • or instanceOfMyExtendingClass.MY_CONST.

More Information

For more information, have a look at:

  • this FAQ entry and the ones that follow it,
  • comments by Anon and Jeff regarding misuses of this form,
  • Enum type as introduced since Java 5 (which, and as mentioned by John, would in many cases definitely be a better idea: more elegant, with the added benefit of type-safety when passing it, and using fairly optimized constructs to lookup and manipulate the values).
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜