Difference between open and override methods in Kotlin?

后端 未结 3 1141
Happy的楠姐
Happy的楠姐 2021-02-18 17:07
open class Base {

    open fun v() {}

    fun nv() {}
}

class Derived() : Base() {

    override fun v() {}
}

This is an example. Can someone please

3条回答
  •  情深已故
    2021-02-18 17:24

    Yes, both open keywords are mandatory in your example.


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

    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.

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


    Edit: Because I saw some confusion in the comments.

    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

    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!

提交回复
热议问题