static静态代码块的使用(单例)

1.声明一个Person类:

package com.xuzhiwen.test1;

public class Person {
    public int age;
    public String name;
    
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

2.声明一个带静态代码块的类:

package com.xuzhiwen.test1;

public class StaticTest {
    public static Person p ;
    static{
        p = new Person();
    }
    
    
    public static Person getPerson(){
        return p;
    }
}

3. 写一个测试类:

package com.xuzhiwen.test1;

public class Test {
    public static void main(String[] args) {
        Person p1 = StaticTest.getPerson();
        Person p2 = StaticTest.getPerson();
        System.out.println(p1==p2);
    }
}

4.运行结果为:

 

posted @ 2017-07-26 10:00  beibidewomen  阅读(561)  评论(0编辑  收藏  举报