Java编程中如何定义全局常量

Class定义常量方法(推荐方法)

//final修饰符
public final class Constants {
    //私有构造方法
    private Constants() {}

    public static final int ConstantA = 100;
    public static final int ConstantB = 100;
    ......
}

采用“类.常量名”方法进行调用。需要私有化构造方法,避免创建该类的实例。同时不需让其他类继承该类。

如果多处需要访问工具类中定义的常量,可以通过静态导入(static import)机制,避免用类名来修饰常量名。

Interface定义常量方法

public interface Constants {
    int ConstantA = 100;
    int ConstantB = 100;
    ......
}

在interface中声明的字段,虚拟机在编译时自动加上public static final修饰符。使用方法一般是“接口.常量名”。也可以通过实现该接口,直接访问常量名,即常量接口模式。

常量接口:即接口中不包含任何方法,只包含静态的final域,每个域都导出一个常量。使用这些常量的类实现这个接口,以避免用类名来修饰常量名。

常量接口模式是对接口的不良使用。具体参考如下:

The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants. These interfaces should be regarded as anomalies and should not be emulated.

区别

上述两种方法对比,interface中定义常量方法生成的class文件比第一种方法的class文件更小, 且代码更简洁, 效率更高.

但是在java中会产生问题,主要是java的动态性,java中一些字段的引用可以在运行期动态进行。某些场景下,部分内容改变可只进行部分编译。具体例子参考文档Java Interface 是常量存放的最佳地点吗?

该文推荐使用Class定义常量,但采用private修饰符,通过get方法获取常量。这种方案可以保证java的动态性。

public class A{
    private static final String name = "bright";
    public static String getName(){
        return name;
    }

补充一个简单地例题。

温度转换

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

输入一个华氏温度,输出摄氏温度,其转换公式为:C=5(F-32)/9。

Input

输入数据只有一个实数,即华氏温度。

Output

输出数据只有一个,即摄氏温度,保留2位小数。

Sample Input

32.0

Sample Output

0.00

Hint

 

Source

import java.util.Scanner;

public class Main {

	private static final double PI = 3.1415926535;

	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		int r,h;
		double dc,ds,cs,v;
		r = in.nextInt();
		h = in.nextInt();
		dc = 2 * PI * r;
		ds = PI * r * r;
		cs = dc * h;
		v = ds * h;
		System.out.printf("%.2f %.2f %.2f %.2f\n",dc,ds,cs,v);
		}
	}

其中,下面的截图就是我需要的全局常量

 

 

PS.顺口吐槽一下变态的线代老师,祝您越来越强(秃)。

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值