Kotlin 中的“开放"和“公开"有什么区别? [英] What is the difference between 'open' and 'public' in Kotlin?
问题描述
我是 Kotlin 的新手,我对 open
和 public
关键字感到困惑.谁能告诉我这些关键字之间的区别?
I am new to Kotlin and I am confused between open
and public
keywords. Could anyone please tell me the difference between those keywords?
推荐答案
open
关键字的意思是为扩展打开":
The open
keyword means "open for extension":
类上的open
注解与Java的final
相反:它允许其他人从这个类继承.默认,Kotlin中的所有类都是final
,对应于Effective Java, Item 17: Design and document for继承,否则禁止.
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.
你还需要明确你想要覆盖的方法,也用 open
标记:
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() {}
}
public
关键字充当可见性修饰符,可应用于类、函数等.请注意,public
是默认值,如果没有明确指定其他内容:
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:
如果你没有指定任何可见性修饰符,默认使用public
,这意味着你的声明在任何地方都可见
If you do not specify any visibility modifier,
public
is used by default, which means that your declarations will be visible everywhere
这篇关于Kotlin 中的“开放"和“公开"有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!