go to previous page   go to home page   go to next page

Answer:

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. Methods can't change the object, even if they have a reference to it. All they can do is call the object's public methods.

class ImmutablePoint
{
  private int x, y;

  public ImmutablePoint( 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(); //  call a public method

    p.x = 77 ; // WRONG! can't do this 
  }
}

class PointTester
{
  public static void main ( String[] args )
  {
    ImmutablePoint pt =  new ImmutablePoint( 4, 8 );

    pt.print(); // call a public method
    
    pt.x = 88;  // WRONG! can't do this

    PointPrinter pptr = new PointPrinter();

    pptr.print( pt ); // ca
        
  }
}

Since ImmutablePoint objects are immutable, a constructor is needed to initialize instance variables to their permanent values.

QUESTION 13:

(Thought Question:) Would it be possible to write a PointDoubler class for ImmutablePoint objects?