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

前端 未结 5 662
别那么骄傲
别那么骄傲 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:41

    This question is old. But I would like to mention an other approach. Using Enums for declaring constant values. Based on the answer of Nandkumar Tekale, the Enum can be used as below:

    Enum:

    public enum Planck {
        REDUCED();
        public static final double PLANCK_CONSTANT = 6.62606896e-34;
        public static final double PI = 3.14159;
        public final double REDUCED_PLANCK_CONSTANT;
    
        Planck() {
            this.REDUCED_PLANCK_CONSTANT = PLANCK_CONSTANT / (2 * PI);
        }
    
        public double getValue() {
            return REDUCED_PLANCK_CONSTANT;
        }
    }
    

    Client class:

    public class PlanckClient {
    
        public static void main(String[] args) {
            System.out.println(getReducedPlanckConstant());
            // or using Enum itself as below:
            System.out.println(Planck.REDUCED.getValue());
        }
    
        public static double getReducedPlanckConstant() {
            return Planck.PLANCK_CONSTANT / (2 * Planck.PI);
        }
    
    }
    

    Reference : The usage of Enums for declaring constant fields is suggested by Joshua Bloch in his Effective Java book.

提交回复
热议问题