Arghya Pal
Arghya Pal

Reputation: 5

How to create a class as immutable in java which is having many fields?

I have got an interview question where interviewer asked me, "How will you create an immutable class in java, which class will have more than 100 fields in it?"

As we know to create immutable class we need to declare a class as final, need to declare all the fields as final and there should not be any setter method present in that class. We need to initialize those field in the constructor.

But what will happen when we have more than 10 fields or more fields? We can not pass all the fields in the constructor right? In this scenario, how can we create an immutable class?

Upvotes: 0

Views: 1073

Answers (1)

Austin Schaefer
Austin Schaefer

Reputation: 696

The field count here is irrelevant, even if having more than a few fields in one class is horrible design and is a sign the class should be refactored. To make a class immutable, you need the following:

  1. No setter methods. this means you either want a Builder inner class which sets the values of your fields before calling the constructor, or simply include all fields as constructor parameters (highly recommended against).
  2. Declare the class as final. This prevents classes from extending and calling super.
  3. If you have non-primitive fields inside your immutable class, you'll need to copy them and return the copy each time you make a change to them.

Btw, as far as I'm aware, Java constructors can handle 255 parameters. So for this interview, constructor parameters would be an option.

Upvotes: 3

Related Questions