Make an interface for Item and Trap which contains the methods they should share.
public interface GameObject {
String getName();
Image getIcon();
}
You can then create the Item and Trap classes by implementing this interface. For example
public class Trap implements GameObject {
private String name;
private Image icon;
public GameObject(String name, Image icon) {
this.name = name;
this.icon = icon;
} ...
By declaring this class implements GameObject it means we have to create the getName and getIcon methods. You do this by using an @Override annotation.
public class Trap implements GameObject {
private String name;
private Image icon;
public GameObject(String name, Image icon) {
this.name = name;
this.icon = icon;
}
@Override
public String getName() {
return name;
}
@Override
public Image getIcon() {
return icon;
}
}
Now that it implements GameObject we can add it to a list that holds GameObject types
List<GameObject> special = new ArrayList<>();
myList.add(new Trap(myTrapName, myTrapImage));
myList.add(new Item(myItemName, myItemImage));
We can then call the methods without worrying if that particular GameObject is an Item or a Trap
for (GameObject obj : special) {
System.out.println(obj.getName());
}
TrapandItemare completely different classes but share two variables.specialneeds to store many different instances ofTrapandItem.