What happens when a class is immutable?

devquora
devquora

Posted On: Jun 25, 2024

 

An immutable class is a class whose state cannot be modified after it is created. Once an object of an immutable class is created, it cannot be modified in any way.

Here are some popular characteristics of immutable classes:

  • All fields of the class are final and therefore cannot be modified after the object is created.
  • The class has no setter methods, so the values of the fields cannot be changed once they are set in the constructor.
  • The class should not provide any methods that can modify its state.
  • If a class has mutable fields (like collections) it should return a new instance of the collection with the new state, instead of modifying the existing one.
  • The class should be thread-safe since it can be shared among multiple threads without the need for explicit synchronization.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Core Java Interview Questions

    Explain the significance of class loaders in Bootstrap?

    Classloaders in Java load classes into the virtual environment, converting named classes into binary form. They load essential classes, such as java.lang.Object, on demand. Java Runtime Environment in..

    Core Java Interview Questions

    What is the difference between JDK, JRE, and JVM?

    JVM (Java Virtual Machine) executes Java bytecode, providing a runtime environment. JRE (Java Runtime Environment) includes JVM and necessary libraries. JDK (Java Development Kit) contains JRE and dev..

    Core Java Interview Questions

    What are the various access specifiers in Java?

    Access specifiers in Java determine the access scope of classes, methods, and fields. They include public (accessible from anywhere), protected (accessible within the same package and subclasses), def..