简体   繁体   English

Kotlin vs Java @Overrides

[英]Kotlin vs Java @Overrides

As shown here, https://stackoverflow.com/a/16639438/8949356 , in Java you can override the function of a declared class when it is public 如此处所示, https://stackoverflow.com/a/16639438/8949356 ,在Java中,您可以在公开时覆盖声明的类的功能

But I want to know how to do this exact same code in Kotlin, I've tried a lot but haven't found anywhere something on this topic. 但我想知道如何在Kotlin中完成相同的代码,我已经尝试了很多,但没有找到关于这个主题的任何地方。 And I could just go and do this in Java but the rest of my code is in Kotlin, plus I just can't stay with this kind of doubt; 我可以用Java来做这个,但我的其余代码都在Kotlin中,而且我不能忍受这种怀疑; Kotlin feels like a great tool to me and want to learn it all. Kotlin对我来说感觉像是一个很好的工具,想要学习它。

If you want to override method, Use override keyword. 如果要覆盖方法,请使用override关键字。

Like this. 像这样。

override fun addNumber(i : Int) {
  val sum = i+10
}

You must declare method that be overrided with open keyword. 您必须声明用open关键字覆盖的方法。 If you don't, You can't override it. 如果不这样做,则无法覆盖它。

open fun addNumber(i : T)

You can override functions and properties with the override keyword . 您可以使用override关键字覆盖函数和属性。 Note though, that in Kotlin, classes are not extensible by default, so you have to declare the parent with open (ie open class MyClass() ) if you want to extend it (Java classes are still extensible unless final ). 但是请注意,在Kotlin中,默认情况下类不可扩展,因此如果要扩展它,则必须使用open声明父open class MyClass() (即open class MyClass() )(Java类仍然可以扩展,除非是final )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM