user7
user7

Reputation: 525

Why, while creating an immutable class, are fields declared as private?

While creating an immutable class, all the fields are declared as final so that their value can’t be modified. This is okay, but why do we also declare them as private?

Upvotes: 3

Views: 329

Answers (3)

porfiriopartida
porfiriopartida

Reputation: 1556

public class Person{
   public Date birthDate = new Date(615666470l); 
}

Then any person could have the birthDate updated from outside.

Person porfiriopartida = new Person();
porfiriopartida.birthDate=new Date(931199270); 

If you provide a constructor with the needed starting attributes and then you only allow to get references to the values the that would work.

Also remember not to return the actual object in get methods (at least that are immutable themselves).

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 372704

An immutable object can't change after being created, but that doesn't mean it necessarily has a simple implementation that should be exported to all clients. As an example, take the String type, which uses a lot of crazy behind-the-scenes optimizations to maximize efficiency for common cases (for example, sharing a backing array when using substring). By hiding all the fields of the class, the implementation can try to take advantage of time- or space-saving optimizations and mediate access to the stored data through the public interface. If those fields were public, it would be difficult (if not impossible) to change the implementation after the fact.

In other words, immutability doesn't imply encapsulation or vice-versa.

Hope this helps!

Upvotes: 0

NPE
NPE

Reputation: 500207

If the field is a reference to a mutable object, making it final will prevent the reference from being rebound to a different object. However, the object can still be modified, in effect side-stepping immutability of the containing object.

To prevent this, you can make the field private (if they can't see it, they can't modify it).

For example:

public class Order {
  public final List<OrderLine> order_lines = ...;
}

Here, anyone can come in and modify the order by adding/removing/modifying order lines, even though order_lines is final.

Upvotes: 4

Related Questions