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.运行结果为:

原文地址:https://www.cnblogs.com/beibidewomen/p/7238024.html