Interfaces in Logo

Interfaces are named collections of method signatures in Java.

import java.lang.Math;

// Here's a basic interface for geometric shapes.
interface Geometry {
    double area();
    double perim();
}

// For our example we'll implement this interface on
// Rectangle and Circle classes.
class Rectangle implements Geometry {
    private double width, height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    @Override
    public double area() {
        return width * height;
    }

    @Override
    public double perim() {
        return 2 * width + 2 * height;
    }

    @Override
    public String toString() {
        return "Rectangle{width=" + width + ", height=" + height + "}";
    }
}

class Circle implements Geometry {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }

    @Override
    public double perim() {
        return 2 * Math.PI * radius;
    }

    @Override
    public String toString() {
        return "Circle{radius=" + radius + "}";
    }
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic measure method taking advantage of this
// to work on any Geometry.
class GeometryUtil {
    public static void measure(Geometry g) {
        System.out.println(g);
        System.out.println(g.area());
        System.out.println(g.perim());
    }
}

public class Interfaces {
    public static void main(String[] args) {
        Rectangle r = new Rectangle(3, 4);
        Circle c = new Circle(5);

        // The Circle and Rectangle classes both
        // implement the Geometry interface so we can use
        // instances of these classes as arguments to measure.
        GeometryUtil.measure(r);
        GeometryUtil.measure(c);
    }
}

To run the program:

$ javac Interfaces.java
$ java Interfaces
Rectangle{width=3.0, height=4.0}
12.0
14.0
Circle{radius=5.0}
78.53981633974483
31.41592653589793

In Java, interfaces are similar to those in other languages. They define a contract that classes must adhere to. Classes that implement an interface must provide implementations for all the methods declared in the interface.

The Geometry interface defines two methods: area() and perim(). The Rectangle and Circle classes implement this interface, providing their own implementations of these methods.

The measure method in the GeometryUtil class demonstrates polymorphism. It can work with any object that implements the Geometry interface, calling its area() and perim() methods without needing to know the specific type of the object.

In the main method, we create instances of Rectangle and Circle, and then pass them to the measure method. This shows how interfaces allow for flexible and reusable code.