简体   繁体   English

Interface Vs Final类存储最终变量

[英]Interface Vs Final class to store the final variables

I have a class which contains only final variables. 我有一个class仅包含final变量。 Eg: 例如:

public class Constants
{
    public static final String PREFIX = "some prefix";
    public static final String SUFFIX = "some suffix";
    //and so on...
}

Which type is recommended here - an interface or a final class ? 这里推荐哪种类型 - interfacefinal class

你应该使用Final Class。

如果要创建一个只包含全局可访问的最终常量的类,则应使用enum

Interfaces are used to define a contract. 接口用于定义合同。 In the code you copy paste, these constants should be defined in a final class. 在复制粘贴的代码中,应在最终类中定义这些常量。 Check What is the best way to implement constants in Java? 检查在Java中实现常量的最佳方法是什么?

Global constants as you put it should actually be in a properties file as it allows each application to configure them individually without a code modification. 您放置的全局常量应该实际上位于属性文件中,因为它允许每个应用程序单独配置它们而无需修改代码。 For object specific constants my general rule of thumb on Enum versus static final I typically lean towards how many elements there are to have and how related those elements are. 对于特定于对象的常量,我对Enumstatic final一般经验法则通常倾向于有多少元素以及这些元素的相关性。 If there is a big relation between them such as Suits in a deck of Cards then I would go for the enum. 如果他们之间有很大的关系,如Suits在甲板Cards ,然后我会去枚举。 If it is default age for a user, then this becomes a final as there is no purpose to making it an enum as it would not need to be referenced in many areas. 如果它是用户的默认年龄,那么这将成为最终版本,因为没有目的使其成为枚举,因为它不需要在许多领域中被引用。 These are just some thoughts on each of the ways I have approached it. 这些只是我接触它的每种方式的一些想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM