Interfaces in Miranda

Interfaces are named collections of method signatures.

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 {
    double width, height;

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

    // To implement an interface in Java, we need to
    // implement all the methods in the interface.
    public double area() {
        return width * height;
    }

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

    @Override
    public String toString() {
        return String.format("{%.1f %.1f}", width, height);
    }
}

class Circle implements Geometry {
    double radius;

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

    // The implementation for Circle.
    public double area() {
        return Math.PI * radius * radius;
    }

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

    @Override
    public String toString() {
        return String.format("{%.1f}", radius);
    }
}

public class Interfaces {
    // If a method takes an interface type as a parameter,
    // 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.
    public static void measure(Geometry g) {
        System.out.println(g);
        System.out.println(g.area());
        System.out.println(g.perim());
    }

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

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

To run the program, compile it and then use java to execute:

$ javac Interfaces.java
$ java Interfaces
{3.0 4.0}
12.0
14.0
{5.0}
78.53981633974483
31.41592653589793

In this Java version, we’ve implemented the Geometry interface and created Rectangle and Circle classes that implement this interface. The measure method demonstrates polymorphism by accepting any object that implements the Geometry interface.

To learn more about Java’s interfaces, you can refer to the official Java documentation or various online tutorials.