1. 程式人生 > >Java程式設計中如何定義全域性常量

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

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.順口吐槽一下變態的線代老師,祝您越來越強(禿)。