Answer These Questions? · Can we do this? public class My Class i private My Class(] Yes. I suppose it is a class that can not be instantiated because it has a private constructor Is there any object that could use this private constructor? The code in my class is the only code that can call it
16 Answer These Questions?. • Can we do this? – Yes. I suppose it is a class that can not be instantiated because it has a private constructor. • Is there ANY object that could use this private constructor? – The code in MyClass is the only code that can call it. public class MyClass { private MyClass() { } }
Answer These Questions? · What does this mear? public class My class i public static My class getinstance0() My Class is a class with static method We can call the static method like this MyClass. getInstance0; Why did you use myclass instead of some object name Well, getInstance( is a static method, in other words, it is a class method. We need to use the class name to reference a static method
17 Answer These Questions?.. • What does this mean? – MyClass is a class with static method. – We can call the static method like this: MyClass.getInstance(); • Why did you use MyClass instead of some object name? – Well, getInstance() is a static method, in other words, it is a CLASS method. We need to use the class name to reference a static method. public class MyClass { public static MyClass getInstance() { } }
Answer These Questions What if i put things together? Now can I instantiate a MyClass? Yes public class My Class i private My Class0 i public static My class getlnstanceo i return new My Class(; Can you think of a second way to instantiate an object? MyClass. getInstanceO 18
18 Answer These Questions?… • What if I put things together? Now can I instantiate a MyClass? – Yes • Can you think of a second way to instantiate an object? – MyClass.getInstance(); public class MyClass { private MyClass() { } public static MyClass getInstance() { return new MyClass(); } }
Answer These Questions Can you finish the code so that only one instance of MyClass is ever created?
19 Answer These Questions?…. • Can you finish the code so that only One instance of MyClass is ever created?
Solution public class SIngleton Class private static SIngleton Class singletonInstance M/other usefulinstance variable here private SIngleton Class public static singleton getsingletonInstanceo t if(singletonInstance==null)t singletonInstance= new SIngleton Class(; return singletonInstance; M/other useful methods here 20
20 Solution public class ASingletonClass { private static ASingletonClass singletonInstance; // other useful instance variable here private ASingletonClass() { } public static singleton getSingletonInstance() { if(singletonInstance == null) { singletonInstance = new ASingletonClass(); } return singletonInstance; } // other useful methods here }