A Problem Solved: Comparing Classes of Squares
In this lesson, we will design a simple class of square objects, implement it in two different ways, and then compare these implementations.
Problem statement
Imagine that you are asked to design and implement a class of square objects. Each object should be able to initialize the length of its side, change this length, and report its area.
A brief design
A square has four sides of equal length, and its area is the product of two of these lengths. Constructors can take care of any initialization, so we need only methods such as these:
setSide
—Sets or changes the length of the square’s side to a given valuegetSide
—Returns the length of the square’s sidegetArea
—Returns the area of the square
Using the class
Before we define the class, let’s write some code that will use it. If we name the class Square
, we might write the following statements:
Square box = new Square();
box.setSide(3.5);
System.out.println("A square whose side is " + box.getSide() +
" has an area of " + box.getArea());
The output from these statements would be
A square whose side is 3.5 has an area of 12.25
An implementation
The definition of this class is not difficult to write. Let’s ask a few people to implement the class. Will everyone write the same code? After a short time, we’ll ask two of them—Joey and Zoe—to show and explain their implementations to us.
Here is Joey’s code:
/** Square.java by Joey.A class of squares.*/public class Square{private double side;public Square(){side = 1.0;} // End default constructorpublic Square(double initialSide){side = initialSide;} // End constructorpublic void setSide(double newSide){side = newSide;} // End setSidepublic double getSide(){return side;} // End getSidepublic double getArea(){return side * side;} // End getArea} // End Square
Joey’s code is straightforward. The class Square
has one data ...