3、java中的常量
在Java语言中,主要是利用final关键字来定义常量,通常我们会以public static final 来修饰(编译时常量)。
package com.kevin.test01;
public class Const
{
public static final String sun = "SUN";
public static final String supperFileType = "exe;jar;class";
}
4、实例调试
我们先写一个常量使用的一个实例
package com.kevin.test01;
public class Const {
public static final String sun = "SUN";
public static final String supperFileType = "exe;jar;class";
}
package com.kevin.test01;
public class Common {
public static void main(String [] args){
StringBuffer txt = new StringBuffer();
txt.append("支持的文件类型");
txt.append(Const.supperFileType);
System.out.println(txt.toString());
}
}
运行结果如下:
public class Const {
static final String sun = "SUN";
static final String supperFileType = "exe;jar;class";
public static String getConst(String constName){
switch(constName){
case "sun" :
return sun;
case "supperFileType":
return supperFileType;
default:
return null;
}
}
}
在需要引用常量的地方,我们直接用常量类中的静态方法获取
package com.kevin.test01;
public class Common {
public static void main(String [] args){
StringBuffer txt = new StringBuffer();
txt.append("支持的文件类型");
txt.append(Const.getConst("supperFileType"));
System.out.println(txt.toString());
}
}