The two instance variables can be made private.
MyPoint with better Encapsulation
Here is a revised version of the program.
Now MyPoint objects are immutable because even with a
reference, methods can't make any changes to the object.
class ImmutablePoint
{
private int x, y;
public Point( int px, int py )
{
x = px; y = py;
}
public void print()
{
System.out.println("x = " + x +
"; y = " + y );
}
}
class PointPrinter
{
public void print( ImmutablePoint p )
{
p.print();
p.x = 77 ; // WRONG! can't do this
}
}
class PointTester
{
public static void main ( String[] args )
{
ImmutablePoint pt =
new ImmutablePoint( 4, 8 );
pt.print();
pt.x = 88; // WRONG! can't do this
PointPrinter pptr = new PointPrinter();
pptr.print( pt );
}
}
Since ImmutablePoint objects are immutable,
a constructor is needed to initialize instance variables to their
permanent values.