I am new to Kotlin and I am confused between open
and public
keywords. Could anyone please tell me the difference between those keywords?
public class in Java is about the visibility of class (nothing to do with inheritance : unless a class in java is final, it can be inherited by default). In kotlin all the class are public by default. open method in kotlin means that the method can be overridden, because by default they are not.
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.
If you mark a declaration as private , it will only be visible inside the file that contains the declaration. If you mark it as internal , it will be visible everywhere in the same module.
open modifier marks classes and methods as overridable. You need one per each method you want to be overridable. Now Button is marked as open, so it can be inherited. click() must be explicitly marked as open to be overridable.
The open
keyword means “open for extension“:
The
open
annotation on a class is the opposite of Java'sfinal
: it allows others to inherit from this class. By default, all classes in Kotlin arefinal
, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.
You also need to be explicit about methods you want to make overridable, also marked with open
:
open class Base { open fun v() {} fun nv() {} }
The public
keyword acts as a visibility modifier that can be applied on classes, functions etc. Note that public
is the default if nothing else is specified explicitly:
If you do not specify any visibility modifier,
public
is used by default, which means that your declarations will be visible everywhere
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