java常量如何引用
常量定义与引用方法
在Java中,常量通常通过static final关键字定义。常量的命名规范为大写字母加下划线分隔(如MAX_VALUE)。
定义示例:
public class Constants {
public static final int MAX_SPEED = 120;
public static final String DEFAULT_NAME = "UNKNOWN";
}
类内直接使用
当常量定义在当前类中时,可直接通过常量名引用:
if (currentSpeed > MAX_SPEED) {
System.out.println("Speed limit exceeded");
}
跨类引用
其他类引用常量时需通过类名访问:
String userName = Constants.DEFAULT_NAME;
int speedLimit = Constants.MAX_SPEED;
接口常量
接口中定义的常量默认为public static final,可通过接口名引用:
interface Config {
String APP_VERSION = "1.0.0";
}
String version = Config.APP_VERSION;
枚举常量
对于枚举类型,常量通过枚举实例引用:

enum Color {
RED, GREEN, BLUE
}
Color bgColor = Color.RED;
注意事项
- 基本类型常量在编译期会被直接替换为字面量
- 对象类型常量(如String)在内存中只有一份实例
- 常量应避免使用复杂对象,确保不可变性






