I hope many of you have heard of SINGLETON CLASS in Java. Even if you have not heard then also you must have experienced of such.Today I am going to post how to create a singleton class. Just as the word "single" means literally as "only one", similarly "singleton" here means "only one object". That means all classes that can have at most one object or only one object can be created of a class. You must have experienced this while installing a software. While an installation program is in progress you cannot run another installation program i.e. execute the same >EXE file while it is already in use. Here is the code for you to create a singleton class in Java -->
public final class MyClass{
private static int count = 0; // Optional 0
private int n;
public MyClass() throws Exception {
this (0);
}
public MyClass(int n) throws Exception {
if (count >= 1) //exception object created and thrown
throw new Exception("No more than one instance");
count++;
this.n = n;
}
public String toString() {
return n + "";
}
public static void main(String[] args) throws Exception {
System.out.println(new MyClass(10));
// System.out.println(new MyClass());
}
}
Uncomment the last line , then save it and then compile and run. It will give an output as shown below
But if it is commented then it will run absolutely fine.
Hope this helps :)
public final class MyClass{
private static int count = 0; // Optional 0
private int n;
public MyClass() throws Exception {
this (0);
}
public MyClass(int n) throws Exception {
if (count >= 1) //exception object created and thrown
throw new Exception("No more than one instance");
count++;
this.n = n;
}
public String toString() {
return n + "";
}
public static void main(String[] args) throws Exception {
System.out.println(new MyClass(10));
// System.out.println(new MyClass());
}
}
Uncomment the last line , then save it and then compile and run. It will give an output as shown below
But if it is commented then it will run absolutely fine.
Hope this helps :)
Thanks. Its a good way of creating single object
ReplyDelete