I’m currently working on some school project; we are developing a simple RPG, but I seem to be questioning some of my Java code.
I have an Abstract class called Item, then I have Armor and Weapon classes which both inherit from Item. Both Armor and Weapon have some attributes that Item doesn’t have.
So in my database wrapper, I have a loaditem method, which gets the stats and creates an instance of my class (read comments in code):
public Item loadItem(int itemID)
{
// Setting item, as a Item, as it can be both Weapon or Armor
Item item;
try {
// Build prepared statement
PreparedStatement stmt = con.prepareStatement("SELECT * FROM item WHERE iid = ?");
// Set Parameter
stmt.setInt(1, itemID);
// Execute the query
ResultSet rs = stmt.executeQuery();
// Get row
rs.first();
// Set all values and keys
if(rs.getString("type").equals("weapon")) {
item = new Weapon();
// SetDamage is unique to Weapon, and setDefense to armor
item.setDamage();
}else {
item = new Armor();
item.setDefense()
}
item.setIid(rs.getInt("iid"));
item.setName(rs.getString("name"));
item.setDescription(rs.getString("description"));
item.setSellValue(rs.getInt("sellvalue"));
item.setBuyValue(rs.getInt("buyvalue"));
item.setStrength(rs.getInt("strength"));
item.setAgility(rs.getInt("agility"));
item.setEndurance(rs.getInt("endurance"));
I have no problem setting a instance of Weapon or Armor to item, but it can’t find the methods in the classes.
Do I really need to create both a weapon and an armor object, and return after type?
Yes, if you’re going to call an instance method, the “target” expression of the method call must have a compile-time type which is known to have the appropriate method. The compiler needs to resolve the method calls at compile time. (Any overload resolution is done at compile-time; the actual implementation is decided at execution time based on polymorphism of course.)
It’s unclear why you’d want the
itemvariable in the first place. It sounds like you should just have:That’s assuming you want to return immediately – your code was truncated, so it’s not clear. If you really do need the
itemvariable, you can just assignweaponorarmortoitemwhere I have the return statements above.EDIT: It sounds like that’s the case, so you’d have:
In fact, you may well want to put the code to initialize the weapon into a separate method. Then you could use: