MyPoint with better Encapsulation

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
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?