I am recently asked about java related question in an interview with following code, since I am very new to java and barely code in Java so I really have no idea what the follow
We use Singleton Pattern when we want to have only one object of this class and it will be used every where. So to restrict the class to create many objects, we should use private
for constructor of this class. And create one public
function to return the object of this class.
public class MethodWin {
private int isLoggedOn=0;
private static MethodWin objectMethodWin = new MethodWin();
private MethodWin() { }
public static MethodWin getInstance() {
return objectMethodWin;
}
public void setIsLoggedOn(int value) {
this.isLoggedOn=value;
}
public int getIsLoggedOn() {
return this.isLoggedOn;
}
}
So when we need to create this obect, we should:
MethodWin meth = MethodWin.getInstance();