G.S
G.S

Reputation: 10871

Interface Vs Final class to store the final variables

I have a class which contains only final variables. E.g:

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?

Upvotes: 4

Views: 2712

Answers (4)

SeniorJD
SeniorJD

Reputation: 7202

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.

Upvotes: 0

omartin
omartin

Reputation: 135

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?

Upvotes: 1

Hermann Hans
Hermann Hans

Reputation: 1806

If you are creating a class which contains only globaly accessible final constants you should use enum.

Upvotes: 0

Geek
Geek

Reputation: 23409

You should use a Final Class for this.

Upvotes: 0

Related Questions