I’m using a very simple factory class to create an initialize some of my objects:
public class MyFactory {
public static Superclass createObject(String type) {
Superclass myObject = null;
if (type.equals("type1")) {
myObject = new Subclass();
myObject.setParam("val1");
}
return myObject;
}
}
Not that complex 🙂 No generic code etc., only this way. Nevertheless I get a type mismatch error in Eclipse if I use my factory this way:
Subclass myObj = MyFactory.createObject("type1");
The error says that it cannot convert from Superclass to Subclass, but everywhere I look (Heads First Design Patterns etc.) I can see it this way: return as type the superclass of created subclasses… So why do I get this error :-)? Thank you!
That’s right. It’s the same reason you can’t store a
Numberin anIntegerfor instance (TheNumbercould actually be aDouble!)If you know that
Subclassis returned fromProbeFactory.createProbe("type1")then you can cast it like this:Down-casting should be avoided if possible. Either you design it so that you can do with
or you could try to create a type-safe version of the factory: