This homework exercise means to teach you about the states on an object, and how to avoid redundancy.
As I see it: the goal is to
- be able calculate diameter and area, and store it in the object
- get rid of the redundant states and calculate the values when needed
The circle has one free attribue (the radius) and two derived attributes (diameter and area) which can be calculated anytime when the radius is known.
That means you can just store the radius, and implement the findArea
/findDiameter
methods such that the result is calculated from the radius and then returned:
public double findDiameter() {
return radius*2;
}
public double findArea() {
return Math.PI * radius * radius;
}
Note (naming conventions): the prefix get
indicates that the value can be accessed locally and in an inexpensive way. When the value is expensive to be calculated or loaded, use a different prefix (that way you know about the costs when using the same value often, and can store it as an intermediate result). That's why the methods to be written in this example are prefixed by find
(although I'd use a different prefix personally, that one looks like the data is retrieved by searching it, and in the concrete case here I'd consider the calcluation to be cheap enough to use a get
prefix).