Java constant examples (Create a java file having only constants)

前端 未结 5 672
别那么骄傲
别那么骄傲 2021-01-31 03:14

What is the best practice to declare a java file having only constant?

public interface DeclareConstants
{
    String constant = \"Test\";
}

OR

5条回答
  •  一个人的身影
    2021-01-31 03:40

    Both are valid but I normally choose interfaces. A class (abstract or not) is not needed if there is no implementations.

    As an advise, try to choose the location of your constants wisely, they are part of your external contract. Do not put every single constant in one file.

    For example, if a group of constants is only used in one class or one method put them in that class, the extended class or the implemented interfaces. If you do not take care you could end up with a big dependency mess.

    Sometimes an enumeration is a good alternative to constants (Java 5), take look at: http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html

提交回复
热议问题