What is the difference between 'open' and 'public' in Kotlin?
The open
keyword means “open for extension“ - i.e. it's possible to create subclasses of an open
class:
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, member functions, etc. If a top-level class or function is public
, it means it can be used from other files, including from other modules. 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
class A { ... }
in Java is equal to open class A { ... }
in Kotlin.final class B { ... }
in Java is equal to class B { ...}
in Kotlin.
It is not related with public
.
In Kotlin, everything without access modifiers is public
by default. You can explicitly say public
in the definition, but it is not necessary in Kotlin.
So,
public class A { ... }
and
class A { ... }
are the same in Kotlin.