0
0
Kotlinprogramming~15 mins

Why open keyword is required for inheritance in Kotlin - See It in Action

Choose your learning style9 modes available
Why open keyword is required for inheritance
📖 Scenario: Imagine you are creating a simple app with animals. You want to make a base class Animal and then create a specific animal like Dog that inherits from Animal.In Kotlin, classes are final by default, so you need to use the open keyword to allow inheritance.
🎯 Goal: Learn how to use the open keyword in Kotlin to allow a class to be inherited.
📋 What You'll Learn
Create an open class called Animal with a function makeSound() that prints "Some sound"
Create a class called Dog that inherits from Animal
Override the makeSound() function in Dog to print "Bark"
Create an instance of Dog and call makeSound() to see the output
💡 Why This Matters
🌍 Real World
Understanding the <code>open</code> keyword is important when designing apps that use inheritance, like games with different characters or apps with reusable components.
💼 Career
Many Kotlin jobs require knowledge of class inheritance and how to control it with <code>open</code> and <code>final</code> keywords to write safe and maintainable code.
Progress0 / 4 steps
1
Create an open class Animal
Create an open class called Animal with a function makeSound() that prints "Some sound".
Kotlin
Need a hint?

Remember to use open before the class and the function to allow inheritance and overriding.

2
Create a class Dog that inherits from Animal
Create a class called Dog that inherits from Animal.
Kotlin
Need a hint?

Use class Dog : Animal() to inherit from Animal.

3
Override makeSound() in Dog
Override the makeSound() function in Dog to print "Bark".
Kotlin
Need a hint?

Use override fun makeSound() inside Dog to change the behavior.

4
Create Dog instance and call makeSound()
Create an instance of Dog called dog and call dog.makeSound() to print the sound.
Kotlin
Need a hint?

Create val dog = Dog() and then call dog.makeSound() inside main().