Java

OOP GUIDE / WORK

 

RECTANGLE CLASS 1 SOLUTIONS

 

TASK – CODE ANALYSIS QUESTIONS

 

Consider the following class and answer the questions at the bottom:

 


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;

    }

}

 

 

 

a)    What is the name of the class?

Answer: Rectangle

b)    What is the name of the file that this code gets stored into?

Answer: Rectangle.java

c)     How many instance variables do this class have?

Answer: 5

d)    How many datafields do this class have?

Answer: 5 (datafield is simply a different name for instance variable – they are the same thing)

e)    How many constructors does this class have?

Answer: 0


f)      How many instance methods does this class have?

Answer: 2 (toString() and area())

g)    What type of data does the toString() method return?

Answer: String

h)    Which instance variables does the toString() method use?

Answer: All five instance variables (x, y, w, h and colour)


i)       What type of data does the area() method return?


Answer: double

j)       Which instance variables does the area() method use?

Answer: w and h

k)     Write the code needed to create a rectangle that has (x,y) = (4,9), a width of 6, a height of 3 and a “red” colour.

 

          Answer:

          Since there is no constructor, we have to create the object with the default           constructor and then set each instance variable individually.  (Painful!!!)


         Rectangle r = new Rectangle();

         r.x = 4;

         r.y = 9;

         r.w = 6;

         r.h = 3;

     r.colour = "red";

 

 

l)       Where would your place the above code to construct the rectangle?

Answer:

It can be placed in any other class.  For now, we would most likely place it inside of a main function that is inside a class named something like RectangleTester.

 

m)   What is the statement needed to output to screen the area of the rectangle that you created above?

Answer:

           System.out.println(r.area());