- 方便在没有创建对象的情况下来进行调用(方法/变量)
- 为什么说static块可以用来优化程序性能,是因为它的特性:只会在类加载的时候执行一次。
class Person{
private Date birthDate;
public Person(Date birthDate) {
this.birthDate = birthDate;
}
boolean isBornBoomer() {
Date startDate = Date.valueOf("1946");
Date endDate = Date.valueOf("1964");
return birthDate.compareTo(startDate)>=0 && birthDate.compareTo(endDate) < 0;
}
}
// 静态代码块的作用
class Person{
private Date birthDate;
private static Date startDate,endDate;
static{
startDate = Date.valueOf("1946");
endDate = Date.valueOf("1964");
}
public Person(Date birthDate) {
this.birthDate = birthDate;
}
boolean isBornBoomer() {
return birthDate.compareTo(startDate)>=0 && birthDate.compareTo(endDate) < 0;
}
}
static修饰的执行顺序
父类静态块 --》子类静态块--》父类构造--》子类构造--》常规方法
注意:静态块是在类加载的时候就加载,且只加载一次