Java

OOP GUIDE / WORK

 

POINT CLASS 2

 

Topics

  • Implementing instance methods
  • Calling instance methods
  • Processing object arrays

 

 

TASK – PART 1 – CONSIDER THE FOLLOWING POINT CLASS

 

Copy the following Point class into your IDE:

 

 

public class Point

{

     public double x;

     public double y;

    

     public Point(double x, double y)

     {

           this.x = x;

           this.y = y;

     }

    

     public double distanceFrom(double x2, double y2)

     {

           double dx = x2 - this.x;

           double dy = y2 - this.y;

           return Math.sqrt(dx * dx + dy * dy); 

     }   

}

 

 

 

TASK – PART 2 – TESTING THE POINT CLASS

 

Create another class called PointTester and follow the following steps:

 

  • Add a main function to the PointTester class.

  • Inside main, create a Point object named p1 that is at (4, 6).

  • Create a Point object named p2 that is at (7, 3).

  • Use the distanceFrom() method on p1 to determine the distance between p1 and p2.  Output your result.

  • Use the distanceFrom() method on p2 to determine the distance between p2 and p1.  Output your result.

 

 

TASK – PART 3 – ADDING A NEW METHOD

 

Create a new method also called distanceFrom that gets a Point object as parameter.  It should calculate the distance between the Point you are in (this) to the Point parameter.

Note that having two methods with the same name is called method overloading.  We can have as many methods as we want with the same name as long as they all have different parameter lists.

 

 

TASK – PART 4 – MORE TESTING

 

Inside the main function from Part 2, test your new method on p1 to determine its distance from p2.  Do vice versa as well.  Output your results.

 

 

TASK – PART 5 – PROCESSING A POINT ARRAY

 

Copy the following code to your IDE and add the statements needed to calculate and output the perimeter of the polygon that is contained in the array of points.

 

 

public class PointTester

{

     public static void main(String[] args)

     {

           Point[] polygon = new Point[9];

           polygon[0] = new Point(0, 0);

           polygon[1] = new Point(3, 2);

           polygon[2] = new Point(4, 1);

           polygon[3] = new Point(3, 5);

           polygon[4] = new Point(6, 3);

           polygon[5] = new Point(5, 8);

           polygon[6] = new Point(3, 9);

           polygon[7] = new Point(2, 6);

           polygon[8] = new Point(1, 2);

          

           //Add your code here.

     }

}