File tree 1 file changed +30
-0
lines changed
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .io .*;
2
+
3
+ class Person {
4
+ static Person name = null ;
5
+ public int age = 12 ;
6
+
7
+ // private constructor can't be accessed outside the class
8
+ private Person () {
9
+ }
10
+
11
+ // Factory method to provide the users with instances
12
+ static public Person getInstance () {
13
+ if (name == null )
14
+ name = new Person ();
15
+
16
+ return name ;
17
+ }
18
+ }
19
+
20
+ class PrivateConstructor {
21
+ public static void main (String args []) {
22
+ Person a = Person .getInstance ();
23
+ Person b = Person .getInstance ();
24
+ a .age = a .age + 10 ;
25
+ System .out .println ("Value of a.age = " + a .age );
26
+ System .out .println ("Value of b.age = " + b .age );
27
+ // We changed value of a.age, value of b.age also got updated because both ‘a’
28
+ // and ‘b’ refer to same object, i.e., they are objects of a singleton class.
29
+ }
30
+ }
You can’t perform that action at this time.
0 commit comments