John Doe John Doe - 2 months ago 7
Java Question

One array containing different Object classes

So I've got an Object class

Item
and an Object class
Trap
. These two share variables called
name
and
icon
. I want to be able to put both of these classes into one array called
special
and be able to access the components of
Item
and
Trap
by using
special
. Here's my code that I need to work.

if (special[x][y] == null)
return 0;
System.out.print(special[x][y].icon); /* here's where the issue is */
return 1;


What should
special
be an array of? Should I use an interface? And if so, how? I've been reading everywhere but I don't know how to describe my problem.

Answer

Give this a try:

class Base 
{
    String name;
    Icon icon;
}

class Item extends Base { }

class Trap extends Base { }

List<Base> special = new ArrayList<>();

alternatively, you can make Base an interface, and use the implements keyword instead of extends for Item and Trap.