In an immutable class, why are fields marked as private?

What is the advantage of creating fields when creating an immutable class?

I saw why when creating an immutable class, fields are declared private? but I didn’t understand anything from this post.

Can someone explain the same to me?

+4
source share
7 answers

The best way to explain is an example:

  public class Immutable {
     private final char[] state = "Hi Mom".getChars();

     public char[] getState() {
         return state.clone();
     }
  }

Here we have a properly encapsulated, immutable class. Nothing can change the state (modulo unpleasant reflective tricks).

Now allows JUST to change access to the field:

  public class Immutable {
     public final char[] state = "Hi Mom".getChars();

     public char[] getState() {
         return state.clone();
     }
  }

, getState... ... - :

  Immutable mu = new Immutable();
  mu.state[1] = 'o';

... .

, private. (, .)

- . , . , ( ) , Immutable. , ; state String. , " /".

, ( public) . public, . ()... . , , , . .

+13

. .

, , - , , , , , . - , ? , ?

, , , - , , . .

+2

, public final, . (, , , .)

, private.

+1

. / , , .

0

- - - , .

.

0
final class A{
   final List l = new ArrayList(); 
}

, , final, .

, .

private.

0

public, " " , .

0

All Articles