Start a Project

‘Open’ Keyword used in Kotlin Class

You will discover more about Kotlin “open” keyword in this blog. You’ll discover how to utilize the open keyword with the class name, function name, and variable name, as well as its benefits.

Everyone is aware that the foundation of every Object-Oriented Programming language is inheritance. It is the process of obtaining or applying the traits and qualities of one class through another. Now we are using a keyword in the kotlin class to achieve inheritance.

The ‘open’ Keyword

Since all classes in Kotlin are final by default, which means they cannot be inherited, we must apply the term open in your class to enable inheritance. Let’s use an example to verify.

‘open’ Keyword Use in Inheritance

To inherit one class from another in Kotlin, use the syntax shown below :

In the example above, the class Demo is inherited from the class Main. If you have a used without an keyword class to inherit with another class they will show a warning.

There won’t be an error after adding the keyword, so you can use inheritance with ease.

‘open’ Keyword use in Functions

Kotlin requires explicit modifiers for overridable members and overrides. Like classes, all Kotlin functions are final by default, meaning that you can’t override a function that has a final nature.

In this code, you can see the parent class demo has a function ‘draw’ and the demo class extends with the main class. In the main class are override functions ‘draw’ now we are redefining the function body.

Conclusion

We learned about the ‘Open’ keyword used in kotlin class in this blog.

Visit the link for additional information on the Overriding methods in Kotlin by using keywords.

Thanks for reading this blog. You can also check other blogs from here for more knowledge.

Always be ready for learning 🙂

Exit mobile version