Kotlin中打开和覆盖方法之间的区别? [英] Difference between open and override methods in Kotlin?

查看:83
本文介绍了Kotlin中打开和覆盖方法之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

open class Base {

    open fun v() {}

    fun nv() {}
}

class Derived() : Base() {

    override fun v() {}
}

这是一个例子.有人可以解释一下区别吗? 这里的开放关键字是强制性的吗?

This is an example. Can someone please explain the difference? Is open keyword mandatory here?

推荐答案

是的,在您的示例中,两个open关键字都是必需的.

Yes, both open keywords are mandatory in your example.

您必须区分在类和函数上使用open的情况.

You have to distinguish between the use of open on classes and functions.

:如果要从类继承,则需要在类上使用open关键字.默认情况下,所有类都是final,并且不能从其继承.

Class: You need the open keyword on a class if you want to inherit from it. By default all classes are final and can not be inherited from.

功能:在功能上,您需要open才能覆盖它.默认情况下,所有功能均为final,并且您无法覆盖它们.

Function: On a function you need open to be able to override it. By default all functions are final and you cannot override them.

编辑:因为我在评论中看到了一些困惑.

Because I saw some confusion in the comments.

pokemzok :我有一个内部抽象类,可以不进行任何继承 问题.我也可以根据需要覆盖抽象方法 宣布它们为开放状态

pokemzok: I have an internal abstract class which I can Inherit without any problem. I also can override it abstract methods as I please without declaring them as open

抽象类是要继承的,因为您不能实例化它们.实际上,它们默认情况下不仅是open,而且不能一开始是final. finalabstract不兼容. abstract方法也是如此,它们必须被覆盖!

Abstract classes are meant to be inherited because you cannot instantiate them. in fact they are not just open by default, they cannot be final in the first place. final and abstract are not compatible. The same goes for abstract methods, they have to be overriden!

这篇关于Kotlin中打开和覆盖方法之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆