【问题标题】:Inherit from abstract class with multiply vars in Kotlin在 Kotlin 中从具有乘法变量的抽象类继承
【发布时间】:2017-07-11 12:20:05
【问题描述】:

我有一个带有乘法变量的抽象类:

abstract class Animal(var name: String, var age: Int, var mother: Animal, 
                      var father: Animal, var friends: ArrayList<Animal>)

现在,您可能已经猜到了,我想创建派生自 Animal 的“Cat”、“Dog”、“Parrot”等类。

但是,当我定义 Cat 类时,我不知道名称、年龄、...字段是什么,所以代码无法编译。

class Cat : Animal()

不编译,因为我们需要在这里传递我们还不知道的变量。

另一个问题是: 如何在一个类中启动一个内部类?猫的母亲和父亲也是猫。

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    查看有关inheritance的文档

    由于您有一个主构造函数,您必须将参数传递给super

    abstract class Animal(var name: String, var age: Int, var mother: Animal, 
                          var father: Animal, var friends: ArrayList<Animal>)
    
    class Cat(name: String, age: Int, mother: Animal, 
              father: Animal, friends: ArrayList<Animal>) 
              : Animal(name, age, mother, father, friends)
    

    【讨论】:

    • 谢谢,没有 vars 编译:class Cat(name: String, age: Int, mother: Animal, Father: Animal, friends: ArrayList) : Animal(name, age, mom,父亲,朋友)
    • 是的,因为它没有定义一个新属性,而只是在构造函数 var 中接收它是不必要的。我会更新我的答案
    【解决方案2】:

    您可以在没有构造函数的情况下指定 Animal 类,并仅在子类型中定义构造函数。

    abstract class Animal {
        var name = ""
        var age = 0
        lateinit var mother: Animal
        lateinit var father: Animal
        lateinit var friends: ArrayList<Animal>
    }
    
    class Cat: Animal {
    
        // only initialize the fields you need for this specific type
        constructor(n: String) {
            name = n
        }
    
        // define a second constructor for your second question
        constructor(m: Animal, f: Animal) {
            mother = m
            father = f
        }
    }
    

    【讨论】:

      【解决方案3】:

      附带说明,您可以使用泛型来帮助确定范围

      例如

      abstract class Animal<T : Animal<T>>(
          var name: String,
          var age: Int,
          var mother: T, 
          var father: T,
          var friends: MutableList<Animal>
      )
      
      class Cat(
          name: String,
          age: Int,
          mother: Cat,
          father: Cat,
          friends: MutableList<Animal>
      ) : Animal<Cat>(name, age, mother, father, friends)
      

      【讨论】:

        猜你喜欢
        • 2023-01-19
        • 2011-08-05
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        • 2021-02-23
        • 1970-01-01
        • 2018-03-07
        相关资源
        最近更新 更多