从 java/kotlin 中的父抽象 class 数组调用子 class 函数
Calling child class function from parent abstract class array in java/kotlin
我有这个游戏对象数组列表。我循环遍历数组列表,如果对象的类型是门(GameObject 的子 classes 之一),并且如果其他一些条件匹配,我想从门 class 调用一个函数] 仅此而已 class。这可能吗?我正在使用 Kotlin,但如果你只知道 java 我可能会移植它。
您可以将 is, as? or with operators 与智能转换结合使用。
在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}
}
}
}
我有这个游戏对象数组列表。我循环遍历数组列表,如果对象的类型是门(GameObject 的子 classes 之一),并且如果其他一些条件匹配,我想从门 class 调用一个函数] 仅此而已 class。这可能吗?我正在使用 Kotlin,但如果你只知道 java 我可能会移植它。
您可以将 is, as? or with operators 与智能转换结合使用。
在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}
}
}
}