kotlin - Kotlin 中的 'open' 和 'public' 有什么区别?

我是 Kotlin 的新手,我对 openpublic 关键字感到困惑。谁能告诉我这些关键字之间的区别?

最佳答案

open 关键字的意思是“为扩展而开放”——也就是说,可以创建 open 类的 子类:

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.

您还需要明确说明要使其可覆盖的方法,也用 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/

相关文章:

kotlin - 将列表分成几部分

kotlin - 在 Kotlin 中使用接口(interface)的默认函数实现

arrays - Kotlin - 检查数组是否包含值的惯用方法

android - 具有初始值的 MutableLiveData

Kotlin - 等待函数

android - 运算符 == 不能应用于 Kotlin 中的 'Long' 和 'Int'

java - Kotlin 中字段的 `open` 关键字是什么?

java - Kotlin 中的 Lambda 表达式

java - 在 IntelliJ IDEA : "No MessageCollector" 中编译

java - 为什么使用双冒号 (::) 在 Kotlin 中上课?