Java

OOP GUIDE / WORK

 

RECTANGLE CLASS 3 SOLUTIONS

 

 

TASK – PART 1 – SETUP

 

No solution required.

 

 

TASK – PART 2 – SHORT QUESTIONS

 

a)            The class has 4 instance variables (x, y, width and height)

b)            It has 1 constructor.

c)            It has 1 instance method (area).

 

d)            In the top line of the constructor (header), you will notice that two of the parameters have names that are identical as the instance variables (x and y).  So, in the constructor, in order to access the instance variable x and y, we need to include the word this in front of them.  Since w and h are different than the instance variable names width and height, there is no issue for those variables and this is not needed.

 

TASK – PART 3 – DATA ENCAPSULATION

 

Solution:

 

public class Rectangle

{

   private double width;

   private double height;

   private double x;

   private double y;

 

   public Rectangle( double x, double y, double w, double h)

   {

      this.x = x;

      this.y = y;

      width = Math.abs(w);

      height = Math.abs(h);

   }

 

   public double area()

   {

        return width * height;

   }

  

   public double getWidth()

   {

        return width;

   }

  

   public double getHeight()

   {

        return height;

   }

  

   public double getX()

   {

        return x;

   }

  

   public double getY()

   {

        return y;

   }

  

   public void setX(double tx)

   {

        x = tx;

   }

  

   public void setY(double ty)

   {

        y = ty;

   }

  

   public void setWidth(double tw)

   {

        width = Math.abs(tw);

   }

  

   public void setHeight(double th)

   {

        height = Math.abs(th);

   }

}

 

public class RectangleTester

{

     public static void main(String[] args)

     {

           Rectangle r1 = new Rectangle(0, 0, 32, -15);

           System.out.println(r1.getX());

           System.out.println(r1.getY());

           System.out.println(r1.getWidth());

           System.out.println(r1.getHeight());  

           r1.setX(5);

           r1.setY(4);

           r1.setWidth(-34);

           r1.setWidth(123);

           System.out.println(r1.getX());

           System.out.println(r1.getY());

          System.out.println(r1.getWidth());

           System.out.println(r1.getHeight());

     }

}