我的预期目标是通过一组固定的属性和方法(其名称不会重叠)从现有库中扩展多个类。
直接的解决方案是简单的继承:派生库类并添加属性/方法。但这将是非常重复的,因为所有派生类的属性和方法都相同。最好创建一个包含我需要的所有属性和方法的辅助类,并简单地从库类和辅助类派生扩展类。
但是,由于 Kotlin 中似乎没有可与 C++ 相比的多重继承,我想使用接口使其工作,其中接口将包含我需要的所有属性和方法。
我已经开始使用以下简单的代码来测试接口:
open class LibraryClass{
var x: Int = 0
fun setMyX(x_: Int){
x = x_
}
}
interface MyInterface{
var y: Int
var z: Int
var abc: Int
fun myMethod(y_: Int){
y = y_
z = y*y
}
}
class InheritanceTest: LibraryClass(), MyInterface{
fun print(){
println("My values: $x, $y, $z")
}
}
fun main(){
var test = InheritanceTest()
test.setMyX(1)
test.myMethod(5)
test.print()
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试编译此代码,则会收到以下错误消息:
error: class 'InheritanceTest' is not abstract and does not implement …Run Code Online (Sandbox Code Playgroud) kotlin ×1