Java

OOP GUIDE / WORK

 

LINE CLASS 2

 

Topics

  • Aggregation & Encapsulation

 

 

TASK – PART 1 – SETUP – LINE CLASS & POINT CLASS

 

Start by copying the following Line & Point classes to your IDE.  Notice that the Line class is already using aggregation.

 

 

public class Line

{

     public Point p1;
     public Point p2;

    

     public Line(double x1, double y1, double x2, double y2)

     {

           p1 = new Point(x1, y1);

           p2 = new Point(x2, y2);

     }

}

 

 

 

public class Point

{

     public double x;

     public double y;

    

     public Point(double x, double y)

     {

           this.x = x;

           this.y = y;

     }

}

 

 

 

TASK – PART 2 – USE ENCAPSULATION ON THE POINT CLASS

 

Use encapsulation on the Point class by:

 

  • Making the instance variables private;

  • Providing get methods for x and y; and

  • Providing set methods for x and y.

 

 

TASK – PART 3 – USE ENCAPSULATION ON THE LINE CLASS

 

Use encapsulation on the Line class by:

 

  • Making the instance variables private;

  • Providing get methods for p1 and p2;

  • Providing set methods for p1 and p2.

 

 

TASK – PART 4 – TOSTRING METHODS

 

For convenience, we will add to String methods to both Line and Point

 

  • Add a toString() method to the Point class that returns a string such as

         "(x, y)"

  • Add a toString() method to the Line class that returns a string such as

         "(x1,y1) to (x2,y2)"

 

 

TASK – PART 5 – TESTING THE LINE CLASS

 

Do the following:

 

a)    Create a Line object that has points (4,2) and (9,1).

b)    Output the Line object to screen.

c)     Write the statement needed to output x1 to screen.  (It should be 4.)

d)    Write the statement needed to change y2 to 13 and then output the line to screen.

e)    Output the first point of the line to screen.

f)      Change p1 so that it is now at (2,3).  Output the line to screen.