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
what is `open` keyword for fields in Kotlin?
提问by M.T
In Kotlin open
is the same as not final
in Java for classes and methods.
对于类和方法,在 Kotlinopen
中与final
在 Java 中不同。
What does open
give 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 open
keyword for properties
我open
对属性的关键字感兴趣
updated
更新
open
class can be inherited.open
fun can be overriddenval
property is final
field in java
open
类可以继承。open
乐趣可以被覆盖val
属性是final
java中的字段
what about open
property?
什么open
财产?
回答by user2340612
As you said, the open
keyword 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 override
it (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 open
since 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 中开放方法是可覆盖的,开放类是可扩展的。