Unit #7: 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

 

·        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

e.     Finds the rectangle with the maximum area and prints the cell#, length, width and the area of the same

 

·        Program Code

o   Rectangle.java

o   RectangleTestArray.java

 

Program Output:

How many rectangles do you want to create?

4

Input length for Rectangle#1

12

Input width for Rectangle#1

45

Area of Rectangle#1 = 540

 

Input length for Rectangle#2

2

Input width for Rectangle#2

6

Area of Rectangle#2 = 12

 

Input length for Rectangle#3

6

Input width for Rectangle#3

34

Area of Rectangle#3 = 204

 

Input length for Rectangle#4

22

Input width for Rectangle#4

12

Area of Rectangle#4 = 264

 

 

Rectangle#1 has the maximum area = 540

Length of Rectangle#1 = 12

Width of Rectangle#1 = 45