Learn Kotlin with me — Abstraction
Abstraction explained simply
Understanding Abstraction in Kotlin
If you’re an Android developer you’ve probably encountered the term “abstraction.” But what does it mean, and how do you use it effectively in Kotlin? Let’s break it down.
What is Abstraction?
At its core, abstraction is the process of hiding unnecessary details and exposing only the essential features of an object. Think of it as simplifying complexity.
Example:
The C programming language is an abstraction of machine language.
- It exposes critical components like syntax and keywords, hiding the intricate binary-level operations.
Why Do We Need Abstraction?
Here’s why abstraction is a game-changer in software development:
- Reusable Code: You define general behaviours that multiple classes can implement.
- Maintainability: It’s easier to make changes or fix bugs because you’ve separated implementation from usage.
- Cleaner Code: Your code becomes more organized, improving readability and reducing clutter.
How to Achieve Abstraction in Kotlin
Kotlin provides two primary ways to implement abstraction:
- Abstract Classes
- Interfaces
Abstract Classes
An abstract class is a class that cannot be instantiated directly. It serves as a blueprint for other courses.
Key points:
- Abstract classes can contain abstract methods (without implementation) and concrete methods (with implementation).
- Subclasses of an abstract class must provide implementations for its abstract methods.
Here’s an example:
Explanation:
- The makeSound() function is abstracted to the Dog class, which provides a unique implementation.
- Complexity is hidden inside the individual classes
- The breath () function is concrete, meaning it’s already implemented and reusable by all subclasses.
Interfaces
An interface defines a contract for classes to follow. Unlike abstract classes, interfaces cannot hold state (i.e., they do not have fields).
Key points:
- Interfaces can have abstract methods and default implementations.
- A class can implement multiple interfaces, offering greater flexibility.
Example:
Explanation:
- The Bird class implements both the Flyable and Swimable interfaces.
- It provides its implementation of fly() while using the default implementation of swim().
When to Use Abstract Classes vs. Interfaces
Abstract Classes:
- Use when you need to define shared states or behaviour (e.g., properties).
- Ideal for classes that are closely related.
Interfaces:
- Use when you need multiple inheritances of behaviour.
- Great for defining roles or capabilities (e.g., Flyable, Swimable).
If you want to learn more. Here is a video for you:
Key Takeaways
Abstraction in Kotlin allows you to:
- Simplify complex systems by focusing only on essential details.
- Write reusable, maintainable, and clean code.
- Use abstract classes for shared behaviour and interfaces for modular capabilities.
Your Captain,
Hitesh Kohli
(The Commute 🚀)