Singleton: this & instance

public class Singleton{
    private static final Singleton instance = new Singleton();
    private String name;
    private int age;
    private Singleton(){}
    public static Singleton getInstance(){
        return instance;
    }

    public void instanceSetter(String name, int age){
        instance.name = name;
        instance.age = age;
    }

    public void thisSetter(String name, int age){
        this.name = name;
        this.age = age;
    }

    public void instanceGetter(){
        System.out.println("instance.name: " + instance.name);
        System.out.println("instance.age: " + instance.age);
    }

    public void thisGetter(){
        System.out.println("this.name: " + this.name);
        System.out.println("this.age: " + this.age);
    }

    public static void main(String[] args){
        Singleton s = Singleton.getInstance();
        System.out.println(s);

        System.out.println("Before setter()");
        s.instanceGetter();    //null, 0
        s.thisGetter();    //null, 0
        System.out.println();

        s.instanceSetter("lxw", 26);

        System.out.println("After intanceSetter()");
        s.instanceGetter();    //lxw, 26
        s.thisGetter();    //lxw, 26
        System.out.println();

        s.thisSetter("wxl", 29);

        System.out.println("After thisSetter()");
        s.instanceGetter();    //wxl, 29
        s.thisGetter();    //wxl, 29
    }
}

Output:

lxw@lxw:14:26:52:~$ java Singleton 
Singleton@15db9742
Before setter()
instance.name: null
instance.age: 0
this.name: null
this.age: 0

After intanceSetter()
instance.name: lxw
instance.age: 26
this.name: lxw
this.age: 26

After thisSetter()
instance.name: wxl
instance.age: 29
this.name: wxl
this.age: 29

 

posted @ 2016-06-16 14:30  XiaoweiLiu  阅读(721)  评论(0编辑  收藏  举报