简体   繁体   中英

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

I have this arraylist of GameObjects. I loop through the arraylist, and if the type of the object is door (one of the GameObject's child classes), and if some other conditions match up, i want to call a function from the door class thats only in that class. Is this possible? I'm using Kotlin, but if you only know java i could probably port it.

You can use is, as? or with operators combined with smart casts for that.

In java you can code as below:

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

You can use like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM