...

/

A Problem Solved: Comparing Classes of Squares

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 value
  • getSide—Returns the length of the square’s side
  • getArea—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:

Press + to interact
/** Square.java by Joey.
A class of squares.
*/
public class Square
{
private double side;
public Square()
{
side = 1.0;
} // End default constructor
public Square(double initialSide)
{
side = initialSide;
} // End constructor
public void setSide(double newSide)
{
side = newSide;
} // End setSide
public double getSide()
{
return side;
} // End getSide
public double getArea()
{
return side * side;
} // End getArea
} // End Square

Joey’s code is straightforward. The class Square has one data ...