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();
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

Get hands-on with 1200+ tech skills courses.