It will be a little difficult to explain, but I will try my best.
I want to have several elements that with each click have a different result. Otherwise, they all have the same variables. So basically I have the Item class, and subclasses of Ball, Rope, Book and many, many more. I want to be able to easily add elements if I want. The Item class has the name String, a String description, and the 'onUse' method, which overrides each of the subclasses.
I would like to handle this as dynamic as possible, which means that I need one method in my Frame / Activity (for Android, but Java is applied) to execute the method.
I use this for one method:
public void useItem(Item i)
{
i.onUse();
}
My problem is that I have different items stored in the database. I want to randomly grab one of the elements from the database and point it out; except that I have no way of knowing which of the subclasses, for example, this. I tried to save the data type in the database, but this does not work ... Pseudocode:
String itemType = c.getString(6);
Class itemClass= null;
try {
itemClass = Class.forName(itemType);
} catch (ClassNotFoundException)
e.printStackTrace();
}
Item l = null;
if (itemClass.equals(Ball.class)) {
l = new Ball(name,description);
} else if(lootClass.equals(Book.class)){
l = new Book(name,description);
}
Seeing that there are so many different elements is not very cool since I will need to go through many classes (plus I often get a ClassNotFoundException)
What do you say, Stackoverflow? What would be a better approach?