This exercise builds on the previous one, exploring additional
features: method overloading, method overriding and the use of exceptions to
signal errors. To get started, copy your both files of your Exercise 6
solution to a new directory, then modify the Circle
class in the
following ways:
Overload the constructor with a default version, taking no parameters. This default version should create a circle with a radius of 1.0.
Modify the original constructor so that it throws an instance of
IllegalArgumentException
if the supplied value for radius is \(\leqslant 0\).
Give your exception object the error message “Invalid radius”. Do not
use try
and catch
here; remember that throwing and catching exceptions
are things that happen in different places.
Override the default implementation of the toString()
method with a new
version. When radius is 1.0, for example, this new version should return a
string like this, showing radius to 4 decimal places:
"Circle(radius=1.0000)"
Override the default implementation of the equals()
method so that it
will return true
when the two Circle
objects being compared have
radii that differ from each other by less than 0.00005, or false
in
all other situations.
This is what the new version of the class looks like in UML form:
Next…
Modify the program in the CircleDemo
class so that it helps you to see
whether the overloaded default constructor and the overridden toString()
and equals()
methods are working properly.
Then modify the program so that it attempts to create an invalid Circle
object. Run the program to observe its behaviour, then modify it so that it
catches the exception that is generated.
@Override
annotation in front of your
definitions of the overridden methodsString.format()
method useful when implementing
toString()
□