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

后端 未结 6 1909
面向向阳花
面向向阳花 2021-01-03 19:26

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

6条回答
  •  梦毁少年i
    2021-01-03 19:56

    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

提交回复
热议问题