Exercise 6: A Small Class

Create a directory for this exercise. In this directory, create a file named Circle.java. In this file, define a class named Circle, to represent circular shapes. The class should have the features shown in the following UML diagram:

UML representation of Circle class

The constructor of your class should initialize the radius field to the supplied value. It should NOT do any checking to see if this value is sensible or not.

The area() method should return the area of the circle, computed using the radius field. The perimeter() method should return the circle’s perimeter (i.e., its circumference), again using the radius field.

Now create another file, named CircleDemo.java, in the same directory as Circle.java. In this file, define a class named CircleDemo, containing a small program that creates a Circle object and then calls the methods getRadius(), perimeter() and area() in turn, displaying the values returned by these method calls. The radius for the circle can be a hard-coded value or it can be input by the user, either via the command line or by prompting for input and using a Scanner or Console object to read it. The choice is yours!

Here’s an example of possible program output:

$ java CircleDemo
Radius    = 4.5
Perimeter = 28.274
Area      = 63.617
Tips