Packages and Interfaces  «Prev  Next»

Java Interfaces - Exercise

Creating interfaces in Java

Objective: Modify classes to implement an interface.


Here is an interface called Enclosure as well as two classes, Circle and Square.
interface Enclosure {
  public double perimeter();
  public double area();

class Circle {
  double radius;
  Circle(double radius) {
    this.radius = radius;

class Square {
  double width;
  Square(double width) {
    this.width = width;

Modify the classes Circle and Square so that they both implement the Enclosure interface. You can use the test program below to make sure your modified classes are working properly.
class EnclosureTest {

  public static void main(String[] args) {

    Enclosure[] enclosures = new Enclosure[2];
    enclosures[0] = new Circle(5.0);
    enclosures[1] = new Square(10.0);
    for (int n = 0; n < enclosures.length; n++)
      System.out.println("area = " +
      enclosures[n].area() +", perimeter = " + 


  1. The constant PI is defined in the Math class (Math.PI).
  2. When you run EnclosureTest here are the results you should observe:

    area = 78.53981633974483, perimeter = 31.41592653589793
    area = 100.0, perimeter = 40.0

Source files

We have supplied the code shown above in files called Enclosure.txt and Enclosuretest.txt.
You will find these files in the download sectiion of the website page.

Exercise scoring

The full credit for this exercise is 5 points. To receive full credit, you will need to successfully modify the classes.
You will submit your modified classes.

What to submit?

In the text box below, cut and paste the source code for the modified classes. Click, Submit to submit the code .