Difference between open and override methods in Kotlin?
Solution 1
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!
Solution 2
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.
Solution 3
The
open
annotation on a class is the opposite of Java'sfinal
: it allows others to inherit from this class as by default all classes in Kotlin arefinal
. [Source]
Only after declaring a class as open
we can inherit
that class.
A method can only be overridden
if it is open in the base class. Annotation override
signals the overriding of base method by inheriting class.
Related videos on Youtube
Deepan
Updated on September 15, 2022Comments
-
Deepan about 1 year
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?
-
Stultuske about 6 yearswhy do you tag this with Java? you may want to check this: kotlinlang.org/docs/reference/classes.html
-
-
Sirop4ik over 5 yearsBut what about 'public' keyword? Can I inherit from 'public class'?
-
Willi Mentzel about 2 years@AlekseyTimoshchenko "If you do not specify any visibility modifier, public is used by default, which means that your declarations will be visible everywhere." kotlinlang.org/docs/visibility-modifiers.html
public
on a class has nothing to do with inheritance though.