Tutorial by Examples

The following rules define a simple strategy for creating immutable objects. Don't provide "setter" methods - methods that modify fields or objects referred to by fields. Make all fields final and private. Don't allow subclasses to override methods. The simplest way to do this is to d...
public final class Color { final private int red; final private int green; final private int blue; private void check(int red, int green, int blue) { if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) { throw ...
In this case class Point is mutable and some user can modify state of object of this class. class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public void setX(int ...
The advantage of immutability comes with concurrency. It is difficult to maintain correctness in mutable objects, as multiple threads could be trying to change the state of the same object, leading to some threads seeing a different state of the same object, depending on the timing of the reads and ...

Page 1 of 1