例子一:
class StaticCode{
static{
System.out.println("a");
}
}
class StaticCodeDemo{
static{
System.out.println("a");
}
public static void main(String[] args){
new StaticCode();
new StaticCode();
System.out.println("over");
}
static{
System.out.println("a");
}
}
执行java StaticCodeDemo命令后;
打印顺序:b c a over
例子二:
class StaticCode{
static{
System.out.println("a");
}
public static void show(){
System.out.println("show run");
}
}
class StaticCodeDemo{
static{
//System.out.println("a");
}
public static void main(String[] args){
//new StaticCode();
//new StaticCode();
//System.out.println("over");
//StaticCode.show();
StaticCode s =null;//这是a没执行,因为这样类没有被加载
s = new StaticCode(); //用到类的内容,才能被加载,所以a也没调用
class Student{
private int age;
private static Student s = new Student();
private Student(){}
public static Student getStudent(){
return s;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age();
}
}
单例的两种写法:
第一种写法:
这个是先初始化对象。
称为:饿汉式。
特点:Single类一进内存,就应经创建好了对象。
/*class Single{
private static Single s = new Single();
private Single(){}
public static Single getInstance(){
return s;
}
}*/
第二种写法:
对象呗调用的时候,才初始化,也叫做对象的延时加载。
称为:懒汉式。
//Single类进内存,对象还没有存在,只有调用了getInstance方法时,才建立对象
class Single{
private static Single s = null;
private Single(){}
public static Single getInstance(){
if(s==null){
synchronized(Single.class){
if(s==null)
s = new Single();
}
}
return s;
}