利用关键字 final 指示常量
public class Contants {
public static void main(String[] args){
final double CM_PER_INCH = 2.54;
double paperWidth=8.5;
double paperLength=11;
System.out.println("Paper size in centimeters:"+paperWidth*CM_PER_INCH + " by " + paperLength*CM_PER_INCH);
}
}
关键字 final 表示变量只能被赋值一次。一旦被赋值后,就不能够再更改。(习惯上常量名使用全大写)
类常量:可以在一个类中的多个方法中使用
public class Contants2 {
public static final double CM_PER_INCH = 3;
public static void main(String[] args){
double paperWidth = 8.5;
double paperHeight = 11;
System.out.println("Paper size in centimeters:"+paperWidth*CM_PER_INCH+" by " + paperHeight*CM_PER_INCH);
}
}
使用关键字 static final 设置一个常量类。
如果其他类的方法要使用到该常量,必须定义为 public ,调用Contants2.CM_PER_INCH。
很好