Unit #8: Classes and Objects in Java

 

 

 

 

Problem #1:

The programs below implement the following:

1)    Rectangle.java implements a Rectangle class as specified below (see private variables and public methods below)

2)    RectangleTest.java creates an instance (or object) of the Rectangle class and calls all the public methods

 

Private Variables:

The class will contain two integer private variables – length and width

 

Public Methods:

a)    The class has two constructors:

o   Constructor#1: a default constructor, Rectangle () which sets the length = 0 and width = 0 

o   Constructor #2: a parameter constructor, Rectangle (int a, int b) which sets the length = a and width = b, where a and b are specified input values

b)    public int getLength() : returns the length of the rectangle

c)     public int getWidth() : returns the width of the rectangle

d)    public void setLength(int a) : sets the length of the rectangle to equal  the input value, a (specified by the user)

e)    public void setWidth (int b): sets the width of the rectangle to equal the input value, b (specified by the user)

f)      public int getArea() : computes and returns the area of the rectangle

 

 

Object view of the Class:

·       User Interface View

·       Program Code View

 

 

Program Code

o   Rectangle.java

o   RectangleTest.java

 

Program Output:

Length of the Rectangle = 10

Width of the Rectangle = 12

Area of the Rectangle = 120

Changing the length and width of the Rectangle:

Input Length

34

Input Width

23

Area = 782

 

 

 

Problem #2:

The programs below implement the following:

1)    Rectangle.java implements a Rectangle class as specified above.

2)    RectangleTestArray.java implements the following:

a.     Creates an array (of input size) of type Rectangle.

b.    Creates and stores an instance of the Rectangle class for every cell in the array

c.     Takes integer input values for length and width for every Rectangle object in the array

d.    Computes the area for every Rectangle object in the array

 

·       Program Code

o   Rectangle.java

o   RectangleTestArray.java

 

Program Output:

ow many rectangles do you want to create?

3

Input length for Rectangle

1

Input width for Rectangle

2

Area of Rectangle = 2

 

Input length for Rectangle

3

Input width for Rectangle

4

Area of Rectangle = 12

 

Input length for Rectangle

5

Input width for Rectangle

6

Area of Rectangle = 30