JavaSE encapsulation & immutability

Encapsulation

Encapsulation refers to preventing callers from changing the instance variables directly.

Immutability

Immutability refers to preventing callers from changing the instance variables at all.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
we still want the caller to be able to specify the initial
value—we just don’t want it to change after the object is created.
Constructors to the rescue
*/
public class ImmutableSwan {

private int numberEggs;

public ImmutableSwan(int numberEggs) {
this.numberEggs = numberEggs;
}

public int getNumberEggs() {
return numberEggs;
}
}

Reference

Thanks, mate.
0%