FET FET - 15 days ago 5
Java Question

Switch a SuperClass

I have a

Class
called
Mineral
and other classes which extend this one, like
Gold
,
Iron
and
Coal
.

I'm trying to switch a
Mineral
class, in order to find out which Mineral has been passed through the following
addMineral
method:

public List<Mineral> addMineral(Mineral mineral, int amount){
switch (mineral){
case Gold:
break;
}
}


But I don't know how to insert the classes which extend Mineral as the cases. In fact the example above doesn't work.

Is this achievable? Is this the right way or is there a better solution?

Answer

You cannot switch on arbitrary object.

You cannot switch on the class of an object.

But you can switch on the name of a class of an object:

switch (mineral.getClass().getName()) {
   case "some.pkg.Gold": 
       // some stuff
}

Or you could use mineral.getClass().getSimpleName() and switch on the class name without the package name, etcetera.

However, both switching on the class name and testing using instanceof are often "code smell". If possible, it is better to use polymorphism rather than hard-wiring special case handling for different subclasses in other code; e.g.

if (mineral.hasSomeProperty()) {
    // do stuff
}
Comments