|
15 | 15 | */
|
16 | 16 | public class Problem_01 {
|
17 | 17 |
|
| 18 | + /* In java, when a class is defined it gets a default public constructor. |
| 19 | + * When we talk about inheritance, it allows us to use the properties and methods |
| 20 | + * of the other class. The class which is using the properties and method is |
| 21 | + * called a sub class whereas the class which actually owns those properties and methods |
| 22 | + * is called a super class. |
| 23 | + * For this particular problem, when a constructor is declared as private, |
| 24 | + * it can be accessed by all those classes which can access the private methods |
| 25 | + * of the that class. Moreover, a private constructor will not allow the class to |
| 26 | + * be instantiated */ |
| 27 | + |
| 28 | + private static Problem_01 obj = null; |
| 29 | + |
| 30 | + /** |
| 31 | + * Private Constructor |
| 32 | + */ |
| 33 | + private Problem_01() {} |
| 34 | + |
| 35 | + /** |
| 36 | + * Method to make sure only one instance is created |
| 37 | + * @return {@link Problem_01} |
| 38 | + */ |
| 39 | + public static Problem_01 objectCreationMethod(){ |
| 40 | + /* This logic will ensure that no more than one object can be created at a time */ |
| 41 | + if(obj == null){ |
| 42 | + obj = new Problem_01(); |
| 43 | + } |
| 44 | + return obj; |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Method to display a message |
| 49 | + */ |
| 50 | + public void display(){ |
| 51 | + System.out.println("Singleton class Example"); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Main method to test the execution of program |
| 56 | + * No unit tests needed |
| 57 | + * @param args |
| 58 | + */ |
| 59 | + public static void main(String[] args) { |
| 60 | + /* Creating singleton instance of the class because object cannot |
| 61 | + * be created due to the existence of private constructor. |
| 62 | + * You can instantiate the class here because this main method |
| 63 | + * is inside the Problem_01 class and private methods can be |
| 64 | + * accessed within the class. */ |
| 65 | + Problem_01 singeltonClass = Problem_01.objectCreationMethod(); |
| 66 | + singeltonClass.display(); |
| 67 | + } |
| 68 | + |
18 | 69 | }
|
0 commit comments