29 April 2022

Interfaces

An Interface is a Contract An interface can contains method headers. A class signs the contract by implementing the interface.

We wil begin with a simple example, an interface for shapes.


public interface Shape 
{
    public double perimeter();
    public double area();
    public double diameter();
}

To sign the contract, you implement the interface.


public class Rectangle implements Polygon
{
    private double width;
    private double height;
    public Rectangle(double width, double height)
    {
        this.width = width;
        this.height = height;
    }
    public double perimeter()
    {
        return 2*(width + height);
    }
    public double area()
    {
        return width*height;
    }
    public double diameter()
    {
        return Math.hypot(width, height);
    }
    public int numSides()
    {
        return 4;
    }
}

Polymorphism No, this does not mean looking like this.

picture of a macaw

The Visibility Principle The type of a varible deterimines what methods are visibe. Interfaces are types.

The Delegation Principle The job of executing code is delegated to the object being pointed at.

An History Lesson In java 8, a change was made. Now these items are allowed, too.

The API Guide