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

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

    Neither one. Use final class for Constants declare them as public static final and static import all constants wherever necessary.

    public final class Constants {
    
        private Constants() {
                // restrict instantiation
        }
    
        public static final double PI = 3.14159;
        public static final double PLANCK_CONSTANT = 6.62606896e-34;
    }
    

    Usage :

    import static Constants.PLANCK_CONSTANT;
    import static Constants.PI;//import static Constants.*;
    
    public class Calculations {
    
            public double getReducedPlanckConstant() {
                    return PLANCK_CONSTANT / (2 * PI);
            }
    }
    

    See wiki link : http://en.wikipedia.org/wiki/Constant_interface

提交回复
热议问题