同时在 Kotlin 推广和实施

在 Java 中,你可以这样做:

class MyClass extends SuperClass implements MyInterface, ...

在 Kotlin 有可能做同样的事情吗

65883 次浏览

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

abstract class MySuperClass
interface MyInterface


class MyClass : MySuperClass(), MyInterface, Serializable

当一个类可以实现多个接口时,禁止多个类继承。

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

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

Note that the order of classes and interfaces does not matter.

另外,请注意,对于扩展的类,我们使用圆括号,这个圆括号指的是父类的主构造函数。因此,如果父类的主构造函数接受一个参数,那么子类也应该传递该参数。

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")
}
}