Java

OOP GUIDE / WORK

 

RECTANGLE CLASS 2

 

Topics

  • Constructors, constructor overloading, constructor chaining

 

TASK – PART 1 – SETUP

 

Copy the follow class into your IDE (Eclipse).

 


public
class Rectangle

{

    public double x, y;     //x and y of top left corner

    public double w, h;     //width and height

    public String colour;   //ie: "pink" or "blue"

    

    public String toString()

    {

     String s = "Top left corner: (" + x + "," + y + "), ";

     s = s + "Width: " + w + ", Height: " + h + ", ";

     s = s + "Colour: " + colour;

     return s;

    }

    

    public double area()

    {

     return w * h;

    }

}

 

 

 

TASK – PART 2 – ADDITIONS

 

Add the following constructors.  Notice that we can have multiple constructors as long as each one has a different parameter list.  This is called constructor overloading.

 

CONSTRUCTORS (6)

 

·       It has a constructor that gets five parameters, one for each instance variable.

·       It has a constructor that gets four parameters, one for each of the numeric instance variables.  All of these rectangles will be “black”.

·       It has a constructor that gets four parameters.  It will construct rectangles with an equal width and height – so squares really.  Two of the parameters are for x and y, one that is the side length of the square and one that is for colour.

·       It has a constructor that gets three parameters.  This constructor is the same as the previous one but doesn’t get a colour as it create black rectangles.

·       It has a constructor that gets three parameters.  The first two parameters are for x and y.  The last parameter is for the colour.  The values of w and h will always be set to 1.

·       It has a constructor that gets two parameters for x and y.  The value of w and h are both set to 1.  The value of colour is “black”.

 

 

TASK – PART 3 – CONSTRUCTOR CHAINING

 

Constructor chaining is when one constructor calls another constructor.  This is done by using:

 

     this(parameters);

 

on the very first line inside the constructor.

 

Alter your program above so that Constructors #2 to 6 all use constructor chaining.  So they will all call the first constructor. 

 

TASK – 4 – TESTING YOUR RECTANGLE CLASS

 

Create a class called RectangleTester and follow the following steps:

 

  • Add a main function to the class.

  • Inside main, create six different rectangle objects making use of the six different constructors.

  • Output each rectangle object to screen (making use of its toString() method)