Java Kotlin 中字段的“open”关键字是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49076121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:57:14  来源:igfitidea点击:

what is `open` keyword for fields in Kotlin?

javakotlin

提问by M.T

In Kotlin openis the same as not finalin Java for classes and methods.

对于类和方法,在 Kotlinopen中与final在 Java 中不同。

What does opengive me in the following class for the field marked as open?

open对于标记为的字段,在以下课程中给了我什么open

@MappedSuperclass
abstract class BaseEntity() : Persistable<Long> {
     open var id: Long? = null
}

updatedthis is not duplicate of What is the difference between 'open' and 'public' in Kotlin?

更新这不是重复Kotlin 中的“开放”和“公开”什么区别?

I am interested in openkeyword for properties

open对属性的关键字感兴趣

updated

更新

openclass can be inherited.
openfun can be overridden
valproperty is finalfield in java

open类可以继承。
open乐趣可以被覆盖
val属性是finaljava中的字段

what about openproperty?

什么open财产?

回答by user2340612

As you said, the openkeyword allows you to override classes, when used in the class declaration. Accordingly, declaring a property as open, allows subclasses to override the property itself (e.g., redefine getter/setter). That keyword is required since in Kotlin everything is "final" by default, meaning that you can't overrideit (something similar to C#, if you have experience with that).

正如您所说,open关键字允许您在类声明中使用时覆盖类。因此,将属性声明为open,允许子类覆盖属性本身(例如,重新定义 getter/setter)。该关键字是必需的,因为在 Kotlin 中final,默认情况下一切都是“ ”,这意味着您不能这样override做(类似于 C#,如果您有这方面的经验)。

Note that your class is implicitly declared as opensince it is abstract, hence you cannot create an instance of that class directly.

请注意,您的类是隐式声明的,open因为它是abstract,因此您不能直接创建该类的实例。

回答by Lajos Arpad

final method in Java: A method that cannot be overridden.

Java 中的 final 方法:一种不能被覆盖的方法。

final class in Java: A class that cannot be extended.

Java 中的 final 类:无法扩展的类。

Open classes and methods in Kotlin are equivalent to the opposite of final in Java, an open method is overridable and an open class is extendable in Kotlin.

Kotlin 中的开放类和方法相当于 Java 中的 final 的对立面,在 Kotlin 中开放方法是可覆盖的,开放类是可扩展的。