Updated 30 November 2022
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.
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.
To inherit one class from another in Kotlin, use the syntax shown below :
1 2 3 4 5 6 7 8 |
open class Demo { } class Main : Demo(){ } |
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.
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.
1 2 3 4 5 6 7 8 |
open class Demo { open fun draw() { /*...*/ } } class Main() : Demo() { override fun draw() { /*...*/ } } |
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.
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 🙂
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.