簡體   English   中英

從java / kotlin中的父抽象類數組調用子類函數

[英]Calling child class function from parent abstract class array in java/kotlin

我有GameObjects的這個arraylist。 我循環遍歷arraylist,如果對象的類型是門(GameObject的子類之一),並且如果其他一些條件匹配,我想從門類中調用一個只在該類中的函數。 這可能嗎? 我正在使用Kotlin,但如果你只知道java我可能會移植它。

你可以使用is,as? 或者與運營商結合使用智能模型。

在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
    }
}

你可以像這樣使用:

//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}
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM