简体   繁体   中英

Interface Vs Final class to store the final variables

I have a class which contains only final variables. 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 ?

你应该使用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?

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. If there is a big relation between them such as Suits in a deck of Cards then I would go for the enum. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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