Skip to content

Commit 1c18ee6

Browse files
committed
feat: add ImmutableUser example demonstrating immutability and defensive copying
Implemented ImmutableUser.java to illustrate creation of immutable objects in Java. Showcases best practices: – final class and final fields – no setters – defensive copying of mutable fields (Date) – safe getter design preventing external mutation Includes demonstration of how original mutable references do not affect internal state. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 1375851 commit 1c18ee6

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.util.Date;
2+
3+
// ImmutableUser class example. Demonstrates how to create an immutable class in Java.
4+
public final class ImmutableUser {
5+
// 1. Make class final so it cannot be subclassed
6+
7+
// 2. Make all fields private and final
8+
private final String username;
9+
private final Date dateOfBirth; // Date is mutable, so handle with care
10+
11+
// Constructor performs defensive copying for mutable fields.
12+
public ImmutableUser(String username, Date dateOfBirth) {
13+
this.username = username;
14+
// 3. Perform a defensive copy for mutable objects
15+
this.dateOfBirth = new Date(dateOfBirth.getTime());
16+
}
17+
18+
// 4. No setters — immutability maintained
19+
public String getUsername() {
20+
return username;
21+
}
22+
23+
// 5. Return a copy instead of the original reference to prevent external modification.
24+
public Date getDateOfBirth() {
25+
return new Date(dateOfBirth.getTime());
26+
}
27+
28+
public static void main(String[] args) {
29+
Date dob = new Date();
30+
ImmutableUser user = new ImmutableUser("Alice", dob);
31+
32+
System.out.println("Username: " + user.getUsername());
33+
System.out.println("Date of Birth: " + user.getDateOfBirth());
34+
35+
// Trying to modify original Date object won't affect the ImmutableUser
36+
dob.setTime(0);
37+
System.out.println("Modified Original Date: " + dob);
38+
System.out.println("Immutable User Date of Birth: " + user.getDateOfBirth());
39+
}
40+
}

0 commit comments

Comments
 (0)