【问题标题】:Calling child class function from parent abstract class array in java/kotlin从 java/kotlin 中的父抽象类数组调用子类函数
【发布时间】:2019-04-05 15:58:00
【问题描述】:

我有这个 GameObjects 的数组列表。我遍历数组列表,如果对象的类型是门(GameObject 的子类之一),并且如果某些其他条件匹配,我想从门类中调用一个函数,该函数仅在该类中。这可能吗?我正在使用 Kotlin,但如果你只知道 java,我可能会移植它。

【问题讨论】:

    标签: java kotlin abstract-class abstract


    【解决方案1】:

    您可以为此使用 is, as? or with operators 与智能演员组合。

    【讨论】:

    • in 是指is 吗?而with 根本不是运算符。
    • 是的,不是in,而是is
    【解决方案2】:

    在java中你可以编写如下代码:

    for (GameObject gameObject: GameObjects) {
        if(gameObject instanceof Door ) { // you can add your another condition in this if itself
            // your implementation for the door object will come here
        }
    }
    

    【讨论】:

      【解决方案3】:

      你可以这样使用:

      //Kotlin 1.1
      interface GameObject {
          fun age():Int
      }
      
      class GameObjectDoor(var age: Int) : GameObject{
          override fun age():Int = age;
          override fun toString():String = "{age=$age}";
      }
      
      fun main(args: Array<String>) {
          val gameObjects:Array<GameObject> = arrayOf(
                        GameObjectDoor(1), 
                        GameObjectDoor(2), 
                        GameObjectDoor(3));
          for (item: GameObject in gameObjects) {
              when (item) {
                  is GameObjectDoor -> {
                      var door = item as GameObjectDoor
                      println(door)
                      //do thomething with door
                  }
                  //is SomeOtherClass -> {do something}
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        • 1970-01-01
        • 2020-12-22
        • 2019-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多