Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15497

Calling subclass constructor corresponding to enum value

I have a method which creates a new EntityItem:

    public void processEntityItem(int[] a){
        float x = Float.intBitsToFloat(a[4]);
        float y = Float.intBitsToFloat(a[5]);
        main.entitys.add(new EntityItem(EntityType.values()[a[2]], a[3], x, y, main.mr.getHieght(x, y), Float.intBitsToFloat(a[6]), a[7]));
    }

Each of my EntityItems have an enum (EntityType) value asigned to them and the first argument in the constructor is that enum value. I also have some subclasses of EntityItem which i would like to create either from this method or from the constructor of EntityItem which is this:

    public EntityItem(EntityType type, int ID, float xCoord, float yCoord, float zCoord, float rotation, int mapID) {
        super(type, ID, xCoord, yCoord, zCoord, rotation, mapID);
    }

An example of a subclass of EntityItem constructor:

    public EntityArrow(int ID, float x, float y, float z, float rotation,  int mapID){
        super(EntityType.ARROW, ID, x, y, z, rotation, mapID);
        createModel();
    }

The only way i can think of to do this is to switch through all of the values of the enum type and call the constructor that corresponds to each value. Is there a different way to check if there is a subclass corresponding to the enum value passed and if so call that subclass constructor that doesnt require me to write out every enum value?

Upvotes: 2

Views: 372

Answers (2)

Kai
Kai

Reputation: 110

Create a static factory method in your super class, that contains a switch statement, or create a polymorphic factory method in your enum type.

Upvotes: 0

Paul Bellora
Paul Bellora

Reputation: 55213

If the constructor arguments are always the same, the enum itself could act as the factory instead of your controlling code. For example:

public enum EntityType {

    ARROW {
        @Override
        public EntityItem makeEntity(
                int id,
                float x,
                float y,
                float z,
                float rotation,
                int mapId
        ) {
            // uses subclass
            return new EntityArrow(id, x, y, z, rotation, mapId);
        }
    },
    CIRCLE {
        @Override
        public EntityItem makeEntity(
                int id,
                float x,
                float y,
                float z,
                float rotation,
                int mapId
        ) {
            // uses base class
            return new EntityItem(this, id, x, y, z, rotation, mapId);
        }
    };

    public abstract EntityItem makeEntity(
            int id,
            float x,
            float y,
            float z,
            float rotation,
            int mapId
    );
}

Upvotes: 3

Related Questions