java - Singleton class object referenced by null -


i have singleton class , instance referenced in many places in project. see 1 such place singleton instance assigned null reference.

questions are: 1. point null reference rest of places? 2. if case, how can avoid this?

here code snippet.

public enum test {    instance;        public void fun(){        system.out.println("hello");    }   }  public class main {     public static void main(string[] args) {        test test = test.instance;        test.fun();        test = null;        test.fun();    } } 

no, local variable test in main set null.

test.instance still points single global instance. since enum, can't force test.instance null.


but consider following (anti-)example, of how static reference reset null:

public class test {    public static test instance = new test();     public void fun(){        system.out.println("hello");    }   }  public class main {    public static void main(string[] args) {        test test = test.instance;        test.fun();        test = null; // test null, test.instance still points global instance        test.instance = null; // test.instance null    } } 

Comments