Java 在 Kotlin 中同时扩展和实现
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48391217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extend and implement at the same time in Kotlin
提问by chntgomez
In Java, you can do such thing as:
在 Java 中,您可以执行以下操作:
class MyClass extends SuperClass implements MyInterface, ...
Is it possible to do the same thing in Kotlin? Assuming SuperClass
is abstract and does not implement MyInterface
是否可以在 Kotlin 中做同样的事情?假设SuperClass
是抽象的,不实现MyInterface
采纳答案by s1m0nw1
There's no syntactic difference between interface implementationand class inheritance. Simply list all types comma-separated after a colon :
as shown here:
接口实现和类继承在语法上没有区别。只需在冒号后列出以逗号分隔的所有类型:
,如下所示:
abstract class MySuperClass
interface MyInterface
class MyClass : MySuperClass(), MyInterface, Serializable
Multiple class inheritance is prohibited while multiple interfaces may be implemented by a single class.
禁止多类继承,一个类可以实现多个接口。
回答by Mr.Q
This is the general syntax to use when a class is extending (another class) or implementing (one or serveral interfaces):
这是在类扩展(另一个类)或实现(一个或多个接口)时使用的通用语法:
class Child: InterfaceA, InterfaceB, Parent(), InterfaceZ
Note that the order of classes and interfaces does not matter.
请注意,类和接口的顺序无关紧要。
Also, notice that for the class which is extended we use parentheses, thee parenthesis refers to the main constructor of the parent class. Therefore, if the main constructor of the parent class takes an argument, then the child class should also pass that argument.
另外,请注意,对于扩展的类,我们使用括号,括号是指父类的主要构造函数。因此,如果父类的主构造函数接受一个参数,那么子类也应该传递该参数。
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")
}
}