我是 Kotlin 的新手,我对 open
和 public
关键字感到困惑。谁能告诉我这些关键字之间的区别?
最佳答案
open
关键字的意思是“为扩展而开放”——也就是说,可以创建 open
类的 子类:
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
标记:
open class Base {
open fun v() {}
fun nv() {}
}
public
关键字充当 visibility modifier可以应用于类、函数、成员函数等。如果顶级类或函数是public
,则意味着它可以在其他文件中使用,包括从其他模块中使用。请注意,如果没有明确指定其他内容,则 public
是默认值:
If you do not specify any visibility modifier,
public
is used by default, which means that your declarations will be visible everywhere
关于kotlin - Kotlin 中的 'open' 和 'public' 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49024200/