Skip to content

Commit e3c5aa4

Browse files
authored
Add files via upload
1 parent 9007fd3 commit e3c5aa4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Constructors/PrivateConstructor.java

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}

0 commit comments

Comments
 (0)