Creating Interfaces and Abstract Classes

Object-oriented programming is programming with hierarchies of abstractions—complex applications typically have multiple interfaces, abstract classes, and implementation classes. We heavily rely on interfaces to specify behavior of abstractions and use abstract classes to reuse implementations. So learning about interfaces and abstract classes is a good starting point for learning about building object-oriented hierarchies.

In recent years interfaces have dramatically evolved in Java. In the past, interfaces were permitted to carry only method declarations and no implementation: they could tell a lot about what’s possible, but never did anything—kinda like my boss. In recent versions of Java, interfaces can have default methods, static methods, and even private methods. With such improvements in Java, it’s fair to ask how interfaces in Kotlin measure up to interfaces in modern Java. We’ll start with that question and explore how Kotlin interfaces fare in comparison. Then we’ll explore how abstract classes differ in Kotlin when compared to Java.

Creating interfaces

Semantically, Kotlin interfaces are a lot like Java interfaces, but they differ widely in syntax. You can honor the original design-by-contract intent of interfaces by writing abstract methods in them. In addition, you may also implement methods within interfaces, but without the default keyword that Java requires. Much like the way static methods in Kotlin classes are placed in companion objects, interfaces can also have static methods, but only via companion objects written within the interfaces.

To get a good feel for interfaces in Kotlin, we’ll create an interface with a few abstract methods and a method with implementation. Then we’ll inherit from that interface to see how the implementation gets carried over to the derived class. Finally, we’ll look at the Kotlin way to define static methods for interfaces.

Let’s start with a Remote interface that represents a remote control device.

Get hands-on with 1200+ tech skills courses.