Java

OOP GUIDE / WORK

 

LINE CLASS

 

Topics

  • Aggregation (with no encapsulation)

 

 

TASK – PART 1 – SETUP – LINE CLASS

 

Start by copying this Line class to your IDE.

 

public class Line

{

     public double x1;

     public double y1;

     public double x2;

     public double y2;

    

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

     {

           this.x1 = x1;

           this.y1 = y1;

           this.x2 = x2;

           this.y2 = y2;

     }

    

     //We could add instance methods here...

}

 

 

TASK – PART 2 – SETUP – POINT CLASS

 

Instead of having four doubles for instance variables, we can have two Point objects.  However, to do this, we need to have a Point class to work with. 

 

Copy the following Point class to your IDE.

 

 

public class Point

{

     public double x;

     public double y;

    

     public Point(double x, double y)

     {

           this.x = x;

           this.y = y;

     }

}

 

 

 

TASK – PART 3 – USING AGREGATION

 

Aggregation is simply the concept of using objects as instance variables for other objects.  Instead of having four double data fields, we will switch the Line class’ data fields to be two points. 

Follow these steps:

 

  1. Remove the Line class’ instance variables.

  2. Add the following two instance variables:

     public Point p1;

     public Point p2;

 

  1. We now need to change the constructor.  The constructor’s job is not to initialize (or construct) all of the instance variables (including objects). 

    Replace the constructor by:

 

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

     {

           p1 = new Point(x1, y1);

           p2 = new Point(x2, y2);

     }

 

 

TASK – PART 4 – TESTING THE LINE CLASS

 

Do the following:

 

a)    Create a Line object.

b)    Output the value of the first point’s x-coordinate to screen.

c)     Output the value of the second point’s y-coordinate to screen.

d)    Set the first point’s y-coordinate to 12.