Skip to content

Interface

As the application becomes complex and larger scale, it is essential to make it easy to extend and update as time goes by. The interface is an object-oriented programming technique that allows us to build loosely-coupled and extensible applications.

In this code note, we will cover following topics:

  • Tightly Coupled Classes
  • Intro to Interface
  • Dependency Injections



› Tightly Coupled Classes

In software engineering, coupling refers to a level of dependencies between two classes.

If class Alpha uses class Bravo by creating a Bravo object, then we can describe their relationships as follows:

  • Class Alpha depends on class Bravo.
  • Class Alpha is tightly coupled with class Bravo.

In our example above, if we change a code in the class Rectangle, we must accommodate this change in the Paint class.  This type of simple code change in one class results in a cascading code change in another dependant class.

This kind of inconvenience is a massive problem in large-scale applications. To mitigate this, we must keep these classes as loosely coupled as possible using Interface.



› Definition of Interface

It is a specification that only includes method declarations. It is just a list of methods without the implementations. The interface is also known as a Contract of Behaviors since the listed methods need to be implemented by a Class.

Interface as Variable Type

The type of variable is always stated as its created. There are two styles: the primitive type variables (int, double, char, boolean) and reference-type variables (all objects). We've used an object's class as the type of reference-type variable.

String string = "string-object";
AlphaleafStudent elisa = new AlphaleafStudent("Elisa William", 3.94); //name, gpa

Interface as Method Parameters

The actual benefits of interfaces are reaped when they are used as the type of parameter provided to a method. Since an interface can be used as a variable's type, it can also be used as a parameter type in method calls. For example, the print method in the Printer class of the class below gets a variable of type read.

1
2
3
4
5
public class Printer {
    public void print(Readable readable) {
        System.out.println(readable.read());
    }
}

Interface as Return Type

Interfaces can be used as return types in methods — just like regular variable types. The following example is a class Factory that can be asked to construct different objects that implement the Packable interface.