Java: Can interfaces contain constant variables defined in them?

為{幸葍}努か 提交于 2019-12-10 12:54:51

问题


Can I can create public static final variables in an interface? Can I keep some common constant values defined in these files?


回答1:


Yes, you can:

public interface Constants
{
    public static final int ZERO = 0;
}

However, it's generally reckoned not to be a good idea these days. It's not so bad if the interface has a real purpose as well, and the constants are likely to be used by most of the implementations... but introducing an interface just to make it easier to get to constants is an abuse of the purpose of interfaces, really. (And that's what used to happen a lot.)




回答2:


Yes, you can keep constants in interfaces. BTW, it's considered to be not very good practice.




回答3:


Certainly, public constants can be used declared inside interfaces. One thing, however, if your interface is just going to be placeholders for constants, use enum instead



来源:https://stackoverflow.com/questions/4012124/java-can-interfaces-contain-constant-variables-defined-in-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!