简体   繁体   中英

Efficient Class Organization with Sub Classes and Variables in Java

I am creating a data system to hold a variety of items for a game and I am not sure what organizational style is more efficient. For example I have an Item class, would making a subclass of Weapon and another subclass of Melee which extends Weapon be more or less efficient than just creating several variables in the Item class which holds whether it is a weapon or armor or other and another which holds if it is melee or ranged or a helmet..etc. Or would a combination of these be efficient and organized to the point it is easily flexible to manipulate?

The question is broad, but generally speaking it is best to make subclasses as opposed to storing excessive variables in some base item.

Start with the bases and work your way down.

public class Item {
    private String name;
    ...
}

public class Weapon extends Item {
    ...
}

public class Melee extends Weapon {
    ...
}

public class Ranged extends Weapon {
   ...
}

This way you can define things like

public class Dagger extends Melee {
    ...
}

and you won't have to worry about defining fields common to all items, like a name.

It won't help with the design problem, but since it is a game you may also want to look at Lightweight Java Game Library if you haven't already.

Assuming the attributes of all the Items are related (they all have a durability attribute), it would make sense to have a parent class that stores and deals with that. Likewise, if all Weapons are related (they all have a damage attribute), it would make sense to have a parent class that stores and deals with that.

Since there seems to be a lot of relation between the items, you should create subclasses rather than try and do it case by case. This also allows you to change how said parental attributes are handled (a more efficient, more accurate algorithm) in one place, rather than in several.

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