Abstraction in Kotlin: Using Abstract Classes and Interfaces

Abstraction is a fundamental concept in object-oriented programming languages. It defines an object’s essential properties without requiring a complete function body within a class. In Kotlin, abstraction can be achieved through abstract classes and interfaces. In today’s tutorial, we will see an example of how to apply abstraction in Kotlin.

Abstraction in Kotlin: Using Abstract Classes and Interfaces

Abstraction in Kotlin: Using Abstract Classes and Interfaces

Difference between Abstract class and Interface:

  1. Abstract classes: Represents a base class that provides a blueprint for a subclass in Kotlin. An abstract class can only be inherited into one subclass and support a single inheritance. An abstract class can have both abstract(no implementation) and non-abstract methods(with implementation). It supports a constructor to initialize properties.
  2. Interface classes: It Allows us to define methods that a class should implement but there is no need to define actual implementation. In Kotlin classes can inherit multiple interfaces. This is called multiple inheritance. It does not support constructors to initialize properties. All the member functions are public by default and we can make them protected.

Example of Abstract class in Kotlin:

Example of Interface class in Kotlin:

Conclusion:

Both abstract and interface classes have their unique usages and completely depend on our usages. If we want to define a function with definitions and want to inherit into a single class then the Abstract class is a good choice. But If we want to make common utils functions without their definitions and want to implement multiple inheritance then Interface is a good choice. So keep practicing, Happy coding.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *