java中enum的用法
本文实例讲述了java中enum的用法。分享给大家供大家参考。具体分析如下:
1. 基本用法
sunday, monday, tuesday, wendsday, thursday, friday, saturday;
}
枚举是常量,所以应该用大写。
2. 枚举是对象
枚举隐含地继承了java.lang.enum,所以它具有java.lang.enum的属性和方法。遍历枚举:
public static void main(string[] args) {
for(day day:day.values()) {
system.out.println(day);
}
}
}
3. 枚举可以带字段和方法,以下示例来自官方the java™ tutorials
aobject("field one", "field two");
private string field1;
private string field2;
enumdemo(string val1, string val2){
this.field1 = val1;
this.field2 = val2;
}
public void printfields(){
system.out.println(this.field1);
system.out.println(this.field2);
}
public static void main(string[] args) {
enumdemo.aobject.printfields();
}
}
以下现实中的示例来自官方的java tutorial:
mercury (3.303e+23, 2.4397e6),
venus (4.869e+24, 6.0518e6),
earth (5.976e+24, 6.37814e6),
mars (6.421e+23, 3.3972e6),
jupiter (1.9e+27, 7.1492e7),
saturn (5.688e+26, 6.0268e7),
uranus (8.686e+25, 2.5559e7),
neptune (1.024e+26, 2.4746e7);
private final double mass; // in kilograms
private final double radius; // in meters
planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double g = 6.67300e-11;
double surfacegravity() {
return g * mass / (radius * radius);
}
double surfaceweight(double othermass) {
return othermass * surfacegravity();
}
public static void main(string[] args) {
double earthweight = 120;
for(planet p: planet.values()){
system.out.println(p.surfacegravity());
system.out.println(p.surfaceweight(earthweight/earth.surfacegravity()));
}
}
}
4. 枚举是singleton,可以用枚举来构建一个singleton
instance(new string[]{"arg1", "arg2"});
string[] myargs;
singleton(string[] args){
this.myargs = args;
}
public static singleton getinstance(){
return instance;
}
public static void main(string[] args) {
for(string arg : instance.myargs)
system.out.println(arg);
}
}
希望本文所述对大家的java程序设计有所帮助。