This is a matter of security / encapsulation preference, the most basic encapsulation is the first approach you posted, the second, however, is a more advanced way of encapsulating . This also protects objects passed to the class by cloning.
Consider the following:
public class SomeData { private final Point value; public SomeData (final Point value) { this.value = value; } public Point getValue( ) { return value; } }
now the above snippet looks unchanged (similar to your example). However, there is a gap in this. view the snippet below.
public final static void main(final String[] args) { Point position = new Point(25, 3); SomeData data = new SomeData(position); position.x = 22; System.out.println(data.getValue( )); }
since we only pass a reference to a position variable that we can still change. Cloning this will help protect the variable position:
if we change the declaration from this:
public SomeData (final Point value) { this.value = value; }
before (similar to cloning)
public SomeBetterData(final Point value) { this.value = new Point(value); }
when we call the main method again:
Point position = new Point(25, 3); SomeData data = new SomeData(position); position.x = 22;
the data object will remain unchanged no matter what we do with position . I hope you understand why there is cloning.
source share