Ammu
Ammu

Reputation: 5137

Java immutable class doubt

I am writing a immutable class.One of the instance is an object of another class which is mutable.How can i prevent the modification of the state of that instance.

Upvotes: 1

Views: 120

Answers (2)

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

  1. Make the variable private
  2. Allow access to the fields of variable only via getters( getVarNameProperty1(), getVarNameProperty2() );
  3. Make class final in order to deny inheritance. In the child class one can create a public getter.

Upvotes: 3

Bozho
Bozho

Reputation: 597422

If you provide delegates to all the getters, but don't provide a getter for the field itself. For example:

public final class Foo {
   private Bar bar;

   public String getBarField1() { 
       return bar.getBarField1();
   }
   public String getBarField2() {
       return bar.getBarField2();
   }
}

But there is a thing to consider - how is the field created. If it is passed in constructor, then you have to create a copy of it rather than get the passed object, otherwise the creating code will have reference to the Bar instance and be able to modify it.

Upvotes: 5

Related Questions