3

If we have a singleton class, say:

private static Singleton instance = new Singleton();

private Singleton() {

}

public static Singleton getInstance() {
    return instance;
}

Now we want to do the classic work. Add some global variables and methods, to simplify just think about getters. Imagine we need to global variables, say str1 and str2:

This two variables and their getters must be static or the fact that we are forcing this class to be a singleton is enough to ensure that only one instance of the class wil exists?

To be more precise:

   private String str1;
   private String str2;

          VS

   private static String str1;
   orivate static String str2;

           AND

   public String getStr1();
   public String getStr2();

          VS

   public static String getStr1();
   public static String getStr2();

1 Answer 1

1

The private constructor will enforce having only one instance at a time. You should still follow standard OOP principles .

private static Singleton instance = new Singleton();

    private Singleton() {

    }

    public static Singleton getInstance() {
        return instance;
    }

    private String str1;
    private String str2;

    public String getStr1() { return str1; }
    public String getStr2() { return str2; }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Inside the private constructor we can initialize the variables normally, right? One more question, for you the the "standard oop principle" is to use the static in a getter method?
Ya, you initialize them just like you would normally. That static was a typo when I copy pasted from your question text !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.