1 enum 可以看成class . 同时还能将string转成enum
搜索的网页,大部分是string to enum的。
toString和valueOf是一样,valueOf不能重写,重写toString等于重写valueOf。
package enumtest;
public class testtostring {
public enum Color {
RED("红色", 1), GREEN("绿色", 2), BLANK("白色", 3), YELLO("黄色", 4);
// 成员变量
private String name;
private int index;
// 构造方法
private Color(String name, int index) {
this.name = name;
this.index = index;
}
// 覆盖方法
// @Override
// public String toString() {
// return this.index + "_" + this.name;
// }
}
public static void main(String[] args) {
System.out.println(Color.RED.toString());
//将string "GREEN" 转成 Color.GREEN对象.
Color lt = (Color) Enum.valueOf(Color.class, "GREEN");
//default call toString()
System.out.println(lt);
}
}
运行结果:
comment out toString:
result:
RED
GREEN
with toString:
result:
1_红色
2_绿色
2 how to init final vars
except init vars declearation, and we can init them in all constructors for final vars
public static class FileSaveResult {
private final String contentType;
private final String name;
private final File file;
private final String errMsg;
public FileSaveResult(){
this.contentType = "";
this.name = "";
this.file = null;
this.errMsg = "";
}
public FileSaveResult(String contentType, String name, File file) {
this.contentType = contentType;
this.name = name;
this.file = file;
this.errMsg = "";
}
public FileSaveResult(String errMsg) {
this.contentType = "";
this.name = "";
this.file = null;
this.errMsg = errMsg;
}
.......
}
3 static 内部类适用外部类访问内部类,但是内部类不访问外部类。
静态内部类可以访问外部类所有的静态变量和方法,即使是private的也一样。
static 内部类应用场景
Java集合类HashMap内部就有一个静态内部类Entry。Entry是HashMap存放元素的抽象,HashMap内部维护Entry数组用了存放元素,但是Entry对使用者是透明的。像这种和外部类关系密切的,且不依赖外部类实例的,都可以使用静态内部类。
本项目中static内部类:util 公用的地方。而且符合上述条件,所以用static