Design an Immutable class that has an java.util.Date member

Carvia Tech | May 19, 2019 | 1 min read | 92 views | Multithreading and Concurrency


Design an Immutable class that has an java.util.Date member

As we know that java.util.Date is not immutable, we need to make a defensive copy of java.util.Date field while returning a reference to this instance variable.

Let’s create a hypothetical person class that has name and dob as the only two members.

Immutbale Person Class
import java.util.Date;

class Person {
    private String name;
    private Date dob;

    public Person(String name, Date dob) {
        this.name = name;
        this.dob = new Date(dob.getTime()); (1)
    }

    public String getName() {
        return name;
    }

    public Date getDob() {
        return new Date(dob.getTime()); (2)
    }
}
1 We are creating a new copy of Date field otherwise reference to dob field may leak
2 We are returning defensive copy of Date field instead of directly returning the reference of instance variable.

Multithreading and Concurrency:
  1. Top 20 Java Concurrency Interview Questions and Answers
  2. What is ThreadLocal in Java, where will you use this class
  3. What do you understand by Java Memory Model?
  4. How will you handle ConcurrentModificationException in Java
  5. What is Immutable Class. Why would you choose it? How would you make a class immutable?
  6. What is AtomicInteger class and how it works internally
  7. Discuss internals of a ConcurrentHashmap (CHM) in Java
See all articles in Multithreading and Concurrency
Top articles in this category:
  1. What is Immutable Class. Why would you choose it? How would you make a class immutable?
  2. Can the keys in HashMap be mutable
  3. What is AtomicInteger class and how it works internally
  4. What is difference between HashMap and HashSet
  5. Diamond Problem of Inheritance in Java 8
  6. What are four principles of OOP, How aggregation is different than Composition?
  7. Discuss internals of a ConcurrentHashmap (CHM) in Java



Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info