4

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?

G.S
  • 10,413
  • 7
  • 36
  • 52

4 Answers4

1

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?

Community
  • 1
  • 1
omartin
  • 135
  • 1
  • 16
  • Yes but i think in his case, using an enum is not good: PREFIX and SUFFIX are not a choice if the idea is to store some value to append on front or on the end of a sentence/word. – omartin May 03 '13 at 12:16
0

You should use a Final Class for this.

Geek
  • 23,089
  • 20
  • 71
  • 85
  • Any clarification? why not `interface`? – G.S May 03 '13 at 07:44
  • Think in terms of the already existing API's in Java. How are they doing it ? They are binding the constants in Final classes and not in Interfaces. This is indeed a Java best practice. Research more. – Geek May 03 '13 at 07:48
  • @Aquillo : That was a valid -1. :-) – Geek May 03 '13 at 07:49
  • Why? Because of [Effective Java](http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683) Item 19: Use interfaces only to define types – Sean Patrick Floyd May 03 '13 at 07:59
0

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

Hermann Hans
  • 1,798
  • 1
  • 13
  • 24
0

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.

SeniorJD
  • 6,946
  • 4
  • 36
  • 53