This code should return the same object every time.
there is a part that i dont understand in the code. why to use private identifiers and then set/get method? why to hide your code variables/methods?
public class SingeltonEx {
public static void main(String[] args) {
Singelton singelton=Singelton.getSingelton("Roni");
System.out.println(singelton.getName());//Roni
Singelton singelton2=Singelton.getSingelton("Udi");
System.out.println(singelton.getName());//Roni
singelton2.setName("Ela");
System.out.println(singelton.getName());//Ela
}
}
class Singelton{
private static Singelton objSingelton; // why to hide these
private String name;
private Singelton(String name){
this.name=name;
}
public static Singelton getSingelton(String name) {
if(objSingelton==null){
objSingelton=new Singelton(name);
return objSingelton;
}
else {
return objSingelton;
}
}
public static Singelton getSingelton2(String name) {
if(objSingelton==null)
objSingelton=new Singelton(name);
return objSingelton;
}
public String getName() { // why to use set/get methods?
return name;
}
public void setName(String name) {
this.name = name;
}
}