open class Base { open fun v() {} fun nv() {} } class Derived() : Base() { override fun v() {} }
This is an example. Can someone please explain the difference? Is open keyword mandatory here?
Method overriding means to redefine or modify the method of the base class in its derived class. Thus, it can be only achieved in Inheritance. Following are the conventions that need to be followed for method overriding in Kotlin: The method that needs to be overridden should be open in nature, in the base class.
It means Open classes and methods in Kotlin are equivalent to the opposite of final in Java, an open method is overridable and an open class is extendable in Kotlin. Note: your class is implicitly declared as open since it is abstract, hence you cannot create an instance of that class directly.
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes.
The open keyword symbolizes open for extension. With the open keyword, any other class can inherit from this class. On the other hand, the public keyword is an access modifier. It is the default access modifier in Kotlin.
Yes, both open
keywords are mandatory in your example.
You have to distinguish between the use of open
on classes and functions.
Class: You need the open
keyword on a class if you want to inherit from it. By default all classes are final
and can not be inherited from.
Function: On a function you need open
to be able to override it. By default all functions are final
and you cannot override them.
Edit: Because I saw some confusion in the comments.
I have an internal abstract class which I can Inherit without any problem. I also can override it abstract methods as I please without declaring them as open
Abstract classes are meant to be inherited because you cannot instantiate them. in fact they are not just open
by default, they cannot be final
in the first place. final
and abstract
are not compatible. The same goes for abstract
methods, they have to be overriden!
By default, the functions in Kotlin are defined as final
. That means you cannot override them. If you remove the open
from your function v()
than you will get an error in your class Derived
that the function v
is final and cannot be overridden.
When you mark a function with open
, it is not longer final
and you can override it in derived classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With