9 November 2020

Interfaces and Types

Classes are types; the class represents a blueprint for the creation of a type of data. When we use a an object we can know its state and behavior. All objects of the same type have a common interface which is the public portion of the class.

We are going to meet a new type today, the interface. An interface is a contract. When you make a class, you have the option of signing these contracts. We will make this concrete today by creating an an interface for shapes. In our world, a shape will know how to compute its diameter, perimeter, and area.

You will learn how to sign these contracts and you will learn about the benefits that flow from doing so.

We have seen an example of this. If you have a type T, then implementing Comparable<T> makes objects of type T sortable. To fulfil the terms of the contract, our class must implement the method int compareTo(T that). In addition, the documentation discusses what properties this method should have to fulfil its design contract. Said properties make this method pass a basic sanity test for being a sorting criterion.

Code generated in each section will be present in the directories B and F at the left. Here is the interface we will start with.


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

Any (concrete) class implementing this interface must implement these three methods. This contract is enforced by the compiler.

YouTube Videos

Interfaces, part 1

Interfaces, part 2