【问题标题】:Inheritence of interfaces realizations on KotlinKotlin 接口实现的继承
【发布时间】:2020-10-17 20:22:11
【问题描述】:

首先我必须做两个接口。两者都有很多实现。然后我需要接口,它将继承自前两个接口的随机实现。 “由车身和发动机制成的汽车”示例。

前两个接口:

interface Carcase {
   val aerodynamics: Float 

   fun getAD(){return aerodynamics}
}

interface Engine {
   val power: Int

   fun getP(){return power}
}

还有一些他们的实现:

class BMV: Carcase {
    override val aerodynamics: Float = 1.0f
}
class Volvo: Carcase {
    override val aerodynamics: Float = 1.5f
}


class V1: Engine {
    override val power: Int = 10
}
class V3: Engine {
    override val power: Int = 20
}
class V5: Engine {
    override val power: Int = 30
}

现在接口继承了这两个实现,不管是什么:

// idk if it working or allowed at all
interface Car<S,T>: Carcase, Engine {
    fun getSpeed{
        return( S.getAD() * T.getP() )  //?????
    }
}

因此我想输入类似这样的主代码:

val car1 = Car<BMW, V1>
val car2 = Car<Volvo, V5>

它应该是这样的:

val s1 = car1.getSpeed() // 1.0f * 10
val s2 = car2.getSpeed() // 1.5f * 30

问题:如何正确地进行这种继承?

我可以得到直接答案或一些书籍(在需要的页面上有链接),因为我什至不知道该用谷歌搜索什么。

【问题讨论】:

    标签: class kotlin inheritance interface


    【解决方案1】:

    似乎只创建类然后声明该类的变量更容易:

    class Carcase(val aerodynamics: Float)
    
    class Engine(val power: Int)
    
    val BMV = Carcase(1.0f)
    
    val Volvo = Carcase(1.5f)
    
    

    然后你的Car 类变成:

    class Car(val case: Carcase, val engine: Engine) {
        fun getSpeed =  case.aerodynamics * engine.power
        
    }
    

    【讨论】:

    • 好的,但似乎我需要在汽车之外(或在它的构造函数中)创建 Carcase 和 Engine 的实例,但这并不是我想要的。我想在它的实现中描述这两个接口的所有变体而不创建它的实例,并根据我在 Car 中选择的 carcase 和 engine 创建两者的累积参数 构造函数。
    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-12
    • 2023-03-13
    相关资源
    最近更新 更多