Java常量示例(创建只有常量的java文件) [英] Java constant examples (Create a java file having only constants)

查看:678
本文介绍了Java常量示例(创建只有常量的java文件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明只有常量的java文件的最佳做法是什么?

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

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

OR

public abstract class DeclareConstants
{
    public static final String constant = "Test";
}


推荐答案

两者都没有。使用常量类为常量将它们声明为 public static final ,并在必要时静态导入所有常量。

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;
}

用法:

import static Constants.PLANCK_CONSTANT;
import static Constants.PI;//import static Constants.*;

public class Calculations {

        public double getReducedPlanckConstant() {
                return PLANCK_CONSTANT / (2 * PI);
        }
}

请参阅wiki链接: http://en.wikipedia.org/wiki/Constant_interface

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

这篇关于Java常量示例(创建只有常量的java文件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆