public class Singleton<T> { public static T getInstance() { if (instance == null) instance = new Singleton<T>(); return instance; } private static T instance = null;}Select one:a. Nob. Yes
Question
public class Singleton<T> { public static T getInstance() { if (instance == null) instance = new Singleton<T>(); return instance; } private static T instance = null;}Select one:a. Nob. Yes
Solution
No. The code provided is incorrect. In Java, you cannot create an instance of a type parameter like new T(). Also, the Singleton class is not generic, it should not have <T>. A correct Singleton pattern in Java would look like this:
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null)
instance = new Singleton();
return instance;
}
}
In this corrected version, the Singleton class is not generic and the getInstance() method returns an instance of the Singleton class. If the instance is null, a new Singleton is created.
Similar Questions
Will the following class compile?public class Singleton<T> { public static T getInstance() { if (instance == null) instance = new Singleton<T>(); return instance; } private static T instance = null;}Select one:a. Nob. Yes
How does the Singleton pattern ensure that a class has only one instance?*1 pointBy providing a global variable that holds the instance.B and CBy using a static method to handle instance creation.By making the class constructor private.
Is it possible to create a clone of a singleton object?a.Yesb.No
Q2. How to create a singleton class in multi threaded environment ?
Static methods and variables can be accessed without creating an instance of the class.Question 23Answera.Trueb.False
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.