While reading the book “Programming for Android” by Brown Hardy, I ran into the following code. There is a singleton class:
public class CrimeLab { private static CrimeLab sCrimeLab; private Context mAppContext; public ArrayList<Crime> mCrimes; private CrimeLab (Context appContext){ mAppContext = appContext; mCrimes = new ArrayList<Crime>(); } public ArrayList<Crime> getCrimes() { return mCrimes; } public static CrimeLab get(Context c){ if (sCrimeLab == null){ sCrimeLab = new CrimeLab (c.getApplicationContext()); } return sCrimeLab; } } There is another class in which the CrimeLab class get and getCrimes methods are used:
public class CrimeListFragment extends ListFragment { private ArrayList<Crime> mCrimes; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mCrimes = CrimeLab.get(getActivity()).getCrimes(); } } I am interested in this line of code mCrimes = CrimeLab.get(getActivity()).getCrimes(); . How do we access CrimeLab if we have not created an instance of the CrimeLab class, and only the sCrimeLab variable in CrimeLab is static? I can assume that the prefix s is not taken into account, or I strongly do not understand the principle of singletons.