
Abstract Classes in Kotlin
In Kotlin, an abstract class is a class that cannot be instantiated directly. It is designed to be a base class for other classes, providing common functionality and defining abstract methods that must be implemented by subclasses.
✅ Key Features of Abstract Classes in Kotlin
Abstract Declaration:
Use the
abstract
keyword to declare an abstract class or abstract method.
No Instantiation:
You cannot create objects of an abstract class.
Concrete and Abstract Members:
Abstract classes can have both concrete (implemented) and abstract (unimplemented) methods.
Inheritance:
Subclasses must implement all abstract members unless they are abstract themselves.
📌 Syntax Example
abstract class Shape { abstract fun () fun () { println("Displaying the shape") }}// Subclass implementing abstract classclass Circle : Shape() { override fun () { println("Drawing a Circle") }}fun () { val circle = Circle() circle.draw() // Output: Drawing a Circle circle.display() // Output: Displaying the shape}
⚡ Explanation
abstract class Shape
→ Shape is an abstract class with an abstract methoddraw()
.fun display()
→ A concrete method available for all subclasses.class Circle : Shape()
→ Subclass overrides and implements thedraw()
method.circle.display()
→ Calls the non-abstract method from the parent class.
🔎 Abstract Properties
Abstract classes can also have abstract properties that must be overridden in subclasses.
abstract class Animal { abstract val sound: String abstract fun ()}class Dog : Animal() { override val sound: String = "Bark" override fun () { println("Dog goes $sound") }}fun main() { val dog = Dog() dog.makeSound() // Output: Dog goes Bark}
🚀 When to Use Abstract Classes
When you want to create a base class with shared functionality.
When certain methods or properties must be implemented by subclasses.
When objects of the base class should not be directly instantiated.
If you need further clarification or examples, feel free to ask!