open
- Kotlin course
- Intermediate
- Lesson 7/116
- 5 min
Learn to define inheritable classes with open.
open: inheritable classes
In Kotlin classes are final by default; they cannot be inherited. To make a class inheritable you add the open modifier.
Example: open class Animal(val name: String). This class can now be subclassed. Without open, writing class Dog : Animal() fails to compile. The same rule applies to methods: methods that a subclass may redefine must be marked open.
open methods
To let a method be redefined in a subclass you add the open modifier. By default class methods are final.
Example: open class Animal { open fun sound() { println("sound") } }. Both the class and the method are open. This means a subclass can redefine sound. A method cannot be open in a non-open class; the class must be opened first.
Practice The Animal base class and the Dog subclass
Define an open class named Animal with a primary constructor taking val name: String. Add an open fun sound() method whose body writes println("$name makes a sound"). Define a subclass named Dog that inherits from Animal(name) and whose override fun sound() writes println("$name barks"). In main create a Dog instance and call sound.
Starter code
// Animal base class (open)
// add an open fun sound method
// Dog subclass, inherits from Animal
// add override fun sound
// instantiate Dog in main, call soundSample solution
open class Animal(val name: String) {
open fun sound() {
println("$name makes a sound")
}
}
class Dog(name: String) : Animal(name) {
override fun sound() {
println("$name barks")
}
}
fun main() {
val d = Dog("Rex")
d.sound()
}Expected output
Rex barks
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which definition creates an inheritable class?
- class Animal(val name: String)
- final class Animal(val name: String)
- sealed class Animal(val name: String)
- open class Animal(val name: String) Correct answer
Explanation: The open modifier enables inheritance.
2 Complete the open class definition
open ____ Animal(val name: String) {
open fun sound() { println(name) }
}
open class Animal(val name: String) {
open fun sound() { println(name) }
}
Explanation: open class declares an inheritable class.
3 Match the inheritance patterns
| Term | Meaning |
|---|---|
open class Animal |
Inheritable base class |
class Dog : Animal() |
Subclass declaration |
open fun sound() |
Redefinable method |
Animal(name) |
Base constructor call |