简体   繁体   English

获取给定超类的子类的静态变量

[英]Get static variable of subclass given superclass

This was very difficult for me to word into a question so allow me to explain. 这对我来说很难提一个问题,所以请允许我解释一下。

I have an abstract class Entity and subclasses House and Warehouse . 我有一个抽象类Entity并且子类HouseWarehouse Each subclass has the same static variables with different values. 每个子类具有相同的静态变量,但具有不同的值。

When a button is pressed in my game an Action is created which specifies which Entity subclass gets created and placed in the world. 在我的游戏中按下按钮时,将创建一个Action ,该Action指定要创建哪个Entity子类并将其放置在世界中。 I want to write a generic method to place some Entity to the world using the static variables of which ever subclass it is. 我想编写一个通用方法,使用其子类的静态变量将某些Entity放置到世界上。

I have a class PlaceEntityAction and when the mouse is clicked the appropriate entity will be placed assuming conditions are correct. 我有一个PlaceEntityAction类,当条件正确时,单击鼠标时将放置适当的实体。 How can I pass the Class I want to be placed to this Action so it works with any generic Entity ? 如何将要放置的类传递给此Action,以便它可与任何通用Entity

Here is some dumbed down code: 这是一些愚蠢的代码:

if (mousePressed)) {
    if (some conditions are true) {

        int ex = x pos
        int ey = y pos


        if (world.player.haveFunds(e.COST_ENERGY, e.COST_MONEY,
                    e.COST_RESOURCE)) {
            if (world.places[ex][ey] == 0) {
                world.entities.add(e);
                world.player.addEnergy(-e.COST_ENERGY);
            }
        }
    }
}

So basically how can I get that e to be whatever subclass I pass to the Action since COST_MONEY, etc is static and should be accessed by the Class and not an object? 因此,基本上,如何使e成为传递给Action的子类,因为COST_MONEY等是静态的,应该由Class而不是对象进行访问?

I'm really struggling to express what I want. 我真的很难表达我想要的东西。 Maybe someone can decipher this or provide some other insight regarding my issue. 也许有人可以对此进行解密或提供有关我的问题的其他见解。 I can provide any other information necessary if you want. 如果需要,我可以提供任何其他必要的信息。

EDIT: 编辑:

e is an instance of whichever subclass I previously initialized based on an ID system but I don't like this method. e是我先前基于ID系统初始化的任何子类的实例,但我不喜欢此方法。

Static variables are the wrong approach here, especially since you've already instantiated your entity. 在这里,静态变量是错误的方法,尤其是因为您已经实例化了实体。

Instead, create abstract functions costEnergy() , costMoney() , and so on on the parent class, and implement them (with the correct values) on the child. 而是在父类上创建抽象函数costEnergy()costMoney() ,然后在子级上实现它们(使用正确的值)。

Static variables aren't polymorphic in Java. 静态变量在Java中不是多态的。 An option would be to declare abstract methods getCostEnergy, getCostMoney and getCostResource in Entity, and have each subclass override those methods to return different constants. 一种选择是在Entity中声明抽象方法getCostEnergy,getCostMoney和getCostResource,并让每个子类重写这些方法以返回不同的常量。 Would that work for your scenario? 这适合您的情况吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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