Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

What are the rules for creating Immutable Objects?

Pragya Keshap answered on February 4, 2023 Popularity 2/10 Helpfulness 1/10

Contents


More Related Answers

  • Some parameters are immutable.
  • Declaring an Immutable Variable#

  • What are the rules for creating Immutable Objects?

    0

    As per Java specification, following are the rules for creating an

    Immutable object:

    Do not provide "setter" methods that modify fields or objects

    referred to by fields.

    Make all fields final and private.

    Do not allow subclasses to override methods. The simplest way to

    do this is to declare the class as final. A more sophisticated

    approach is to make the constructor private and construct instances

    in factory methods.

    If the instance fields include references to mutable objects, do not

    allow those objects to be changed.

    Do not provide methods that modify the mutable objects.

    Do not share references to the mutable objects. Never store

    references to external, mutable objects passed to the constructor; if

    necessary, create copies, and store references to the copies.

    Similarly, create copies of your internal mutable objects when

    necessary to avoid returning the originals in your methods

    https://www.digitalocean.com/community/tutorials/how-to-create-immutable-class-in-java

    Popularity 2/10 Helpfulness 1/10 Language java
    Source: Grepper
    Tags: java rules
    Link to this answer
    Share Copy Link
    Contributed on Feb 04 2023
    Pragya Keshap
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.