AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



design-patterns-singleton: can we clone singleton object in java?

Please explain with example can we clone singleton object in java.

design-patterns x 15
singleton x 3
Posted On : 2016-03-17 23:47:29.0
profile Mantu Kumar - anyforum.in Mantu Kumar
8200
up-rate
4
down-rate

Answers


Yes we can clone the singleton class object. Let´s see following example:


public class Singleton implements Cloneable{

public static Singleton singleton;

public static Singleton getSingleton(){
if(singleton==null){
singleton=new Singleton();
}
return singleton;
}
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}

public static void main(String[] args) {

Singleton singleton=Singleton.getSingleton();
System.out.println(singleton);
try{
System.out.println((Singleton)singleton.clone());
}
catch (Exception e) {
// TODO: handle exception
}

}
}

Output:
---------------------------
Singleton@e48e1b
Singleton@12dacd1

It´s printing the different different object. If you want to prevent the cloning just throw some exception in overridden clone method.

Posted On : 2016-03-18 23:39:15
Satisfied : 2 Yes  3 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188249150
Reply This Thread
up-rate
5
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in