Java 中定义常量的几种方法

主要有三种:接口、类和枚举。

接口:

  1. 在接口里定义域(接口中会对域自动加上 public static final ,使之成为常量)
  2. 类实现该接口即可在类中调用该常量

类:

直接用 public static final 定义常量。

枚举:

在枚举类中直接写上常量值。

示例:

public class ConstTest {
public static void main(String[] args) {
Signal sg = new Signal();
System.out.println("interface method: " + sg.RED);
SignalClassField scf = new SignalClassField();
System.out.println("class method: " + scf.RED);
System.out.println("emun method: " + SignalEnum.RED.toString());
}
}
//interface method
interface SignalInterface {
String RED = "InterfaceRED";
String GREEN = "GREEN";
String YELLOW = "YELLOW";
}
class Signal implements SignalInterface {
}
//class method
class SignalClassField {
public static final String RED = "ClassRED";
public static final String GREEN = "GREEN";
public static final String YELLOW = "YELLOW";
}
//enum method
enum SignalEnum {
RED, GREEN, YELLOW
}

输出:

interface method: InterfaceRED
class method: ClassRED
emun method: RED

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD All Rights Reserved.

访客数 : | 访问量 :