Rabu, 28 Juli 2021

Does making all fields Final makes the class Immutable in Java? Example

One of the common misconceptions among many Java Programmers is that a class with all final fields automatically becomes Immutable. This is not correct, you can easily break the immutability of a certain class if the final field it contains is a mutable one, as we'll see in this article. One of the most common examples of this is a java.util.Date fields e.g. birthDay, expirtyDate, or joiningDate sort of fields. You have to be extra cautious to keep your class' immutability intact with mutable fields. The most common mistake in this regard happens when a Java programmer returns a reference of the original object when a client asks like getBirthDay() returns the date object pointed by birthDay field.

Lorem ipsum is simply dummy text of the printing and typesetting industry.

Comments


EmoticonEmoticon