Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between 'open' and 'public' in Kotlin?

I am new to Kotlin and I am confused between open and public keywords. Could anyone please tell me the difference between those keywords?

like image 442
Sagun Raj Lage Avatar asked Feb 28 '18 07:02

Sagun Raj Lage


People also ask

What is the open and public in Kotlin?

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.

What does open mean in Kotlin?

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.

What is difference between internal and private in Kotlin?

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.

What is open modifier in Kotlin?

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.


1 Answers

The open keyword means “open for extension“:

The open annotation on a class is the opposite of Java's final: it allows others to inherit from this class. By default, all classes in Kotlin are final, 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

like image 187
s1m0nw1 Avatar answered Sep 19 '22 17:09

s1m0nw1