abstract
- Kotlin course
- Intermediate
- Lesson 10/116
- 5 min
Learn abstract classes with abstract.
abstract class
An abstract class cannot be instantiated directly and may contain abstract members that subclasses must fill in. An abstract method is declared without a body; a subclass must override it.
Example: abstract class Animal { abstract fun sound(): String }. You cannot write Animal() to instantiate it. A subclass must provide a body with override fun sound(): String. abstract classes are a stronger form of open; they are always open for inheritance.
Inheriting an abstract class
A subclass that inherits an abstract class must fill in all abstract methods with override. Otherwise the subclass must also be abstract.
Example: class Cat : Animal() { override fun sound() = "meow" }. Here Cat fills Animal's abstract sound. Cat is now a concrete class; you can write Cat() to instantiate it. Animal() cannot be instantiated; it is used only through a subclass.
Practice The Animal abstract class and the Cat subclass
Define an abstract class named Animal with a primary constructor taking val name: String. Add an abstract fun sound(): String method. Define a subclass named Cat that inherits from Animal(name) and whose override fun sound(): String returns "$name meows". In main create a Cat instance and print the result of sound().
Starter code
// Animal abstract class
// abstract sound method signature
// Cat subclass, inherits from Animal
// override to return meows
// instantiate Cat in main, print soundSample solution
abstract class Animal(val name: String) {
abstract fun sound(): String
}
class Cat(name: String) : Animal(name) {
override fun sound(): String {
return "$name meows"
}
}
fun main() {
val c = Cat("Whiskers")
println(c.sound())
}Expected output
Whiskers meows
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the abstract method definition
abstract class Animal {
____ fun sound(): String
}
abstract class Animal {
abstract fun sound(): String
}
Explanation: An abstract method is declared without a body.
2 Match the abstract class concepts
| Term | Meaning |
|---|---|
abstract class Animal |
Abstract base class |
abstract fun sound() |
Bodyless method |
override fun sound() |
Filling in subclass |
class Cat : Animal() |
Concrete subclass |
3 <code>abstract class Animal</code> is defined. Which of the following cannot be done?
- Subclassing Animal
- Defining a concrete (bodied) method in Animal
- Instantiating Animal directly Correct answer
- Defining an abstract method in Animal
Explanation: An abstract class cannot be instantiated directly; it is used only through a subclass.