abstract vs interface

ref – https://medium.com/@eneszor95/big-challenge-in-kotlin-interface-vs-abstract-class-520cc234e7c1

Abstract let’s other classes inherit from the abstract class.
Interface, let’s others conform to it.

Interfaces can have abstract methods

We provide a base abstract function. If you over-ride it in your class, it will call it. Otherwise, it will default down to the base abstract function in your interface.

In our example, addMilk is over-ridden. But we did not implement addCoffee, so it calls CoffeeMachineInterface’s addCoffee.


output:
SuporCoffee – Adds Foamy Milk
CoffeeMachineInterface – Coffee is being added…

Interfaces can be properties…but need to be abstract


output:
set() on ‘coffeeAmount’ for SuporCoffee
get() on ‘coffeeAmount’ for SuporCoffee
cup1 has 16 oz of coffee

An interface can be inherited from other interface.

abstract classes cannot be instantiated. You must derive from it, and then instantiate it.

  • an abstract class Person is created. You cannot create objects of the class.
  • the class has a non-abstract property age and a non-abstract method displaySSN. IF you need to override these members in the subclass, they should be marked with open keyword.
  • The class has an abstract method displayJob(). It doesn’t have any implementation and MUST be overridden in its subclasses.

So we create class Teacher and override displayJob. Then when we instantiate it, we can access its own implementation of displayJob and the abstract’s final base function displaySSN.

Also, the practical side of abstract classes is that you can encapsulate a part of implementation that works with the state, so that it cannot be overridden in the derived classes.

Abstract properties can be initialized or abstract. When it is abstract, it cannot be initialized. It must be over-riden in the derived class

Property that are initialized must have keyword ‘open’

Abstract can hold state by using open and initializing a property. We then have the option of over-riding it in a derived class.