Professional Documents
Culture Documents
Kotlin Abstract Classes With Examples
Kotlin Abstract Classes With Examples
We create
abstract classes to provide a common template for other classes to
extend and use.
fun displayDetails() {
Any subclass that extends the abstract class must implement all of its
abstract methods and properties, or the subclass should also be
declared as abstract.
If you recall from the Kotlin Inheritance tutorial, you need to annotate a
class as open to allow other classes to inherit from it. But, you don’t
need to do that with abstract classes. Abstract classes are open for
extension by default.
Similarly, abstract methods and properties are open for overriding by
default.
But, If you need to override a non-abstract method or property, then you
must mark it with the open modifier.
Following are two concrete classes that extend the Vehicle abstract
class and override its abstract methods and properties -
color: String,
weight: Double,
println("Car Started")
}
println("Car Stopped")
color: String,
weight: Double,
println("Bike Started")
println("Bike Stopped")
Let’s now write some code to test our abstract and concrete classes in
the main method -
car.displayDetails()
motorCycle.displayDetails()
car.start()
motorCycle.start()
# Output
Name: Ferrari 812 Superfast, Color: red, Weight: 1525.0, Max Speed: 339.6
Name: Ducati 1098s, Color: red, Weight: 173.0, Max Speed: 271.0
Car Started
Bike Started
Conclusion
Abstract classes help you abstract out common functionality into a base
class. It may contain both abstract and non-abstract properties and
methods. An abstract class is useless on its own because you cannot
create objects from it. But, other concrete (non-abstract) classes can
extend it and build upon it to provide the desired functionality.
I hope you understood how abstract classes work in kotlin. Please ask
any doubts that you might have in the comment section below.