在 Kotlin 中同时扩展和实现

2022-08-31 08:57:57

在Java中,您可以执行以下操作:

class MyClass extends SuperClass implements MyInterface, ...

在 Kotlin 中可以做同样的事情吗?假设是抽象的,不实现SuperClassMyInterface


答案 1

接口实现类继承之间没有语法上的区别。只需列出冒号后以逗号分隔的所有类型,如下所示::

abstract class MySuperClass
interface MyInterface

class MyClass : MySuperClass(), MyInterface, Serializable

禁止多类继承,而单个类可以实现多个接口。


答案 2

这是当一个类扩展(另一个类)或实现(一个或服务器接口)时使用的一般语法:

class Child: InterfaceA, InterfaceB, Parent(), InterfaceZ

请注意,类和接口的顺序无关紧要。

另外,请注意,对于扩展的类,我们使用括号,括号是指父类的主构造函数。因此,如果父类的主构造函数采用参数,则子类也应传递该参数。

interface InterfaceX {
   fun test(): String
}

open class Parent(val name:String) {
    //...
}

class Child(val toyName:String) : InterfaceX, Parent("dummyName"){

    override fun test(): String {
        TODO("Not yet implemented")
    }
}

推荐