Kotlin: Abstract Class & Interface

MJ Manaog
2 min readJan 14, 2021

Let’s talk about a class first.

In Kotlin, all classes are final and public in nature.

Error in Line 5 because you cannot extend the class Shape because it is final by default.

What you can do is add open before the class keyword to make it inheritable. You can also add the open keyword before the fun in declaring a method to override it in the subclass.

But what if you want a single class that can have both optional and required method to override in a class, you can use Abstract.

What does it mean? For example, you have a Shape class, and your shape has a fixed or default color that you want to share for all shapes but has different computations in terms of Area, Perimeter, etc depending on a specific shape. An abstract class is the best fit for your needs.

  • Line 9— we declared an abstract class named Shape.
  • Line 10 — we declared lateinit variable, then we initialized it inside the init{} method and reassigned it in shapeColor in Line 12
  • Line 18— we declared a method that can have a default value for all shape
  • Line 21–23 — we declared an abstract method that needed to be overridden to the subclasses.
  • Line 26 — we created a normie class with primary constructors l and w and we extended the abstract class Shape()
  • Line 27–29— we override the required method in the abstract class Shape()

HMMM okay. So how about Interfaces?

Basically, an abstract can do what an interface can. The difference is, the abstract class can have constructors, an init body, and fields so we can properly hold state.

You can use an interface when you only want to share behavior with the class but not the code between a set of objects. But if you need both, use an abstract class.

I’m still learning, please leave a comment if there’s something I need to improve/learn/elaborate. Thank you!

--

--