Reputation: 4199
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!
Upvotes: 2
Views: 425
Reputation: 4171
Usually you want to treat the objects of the same factory similarly, that is why Superclass is created to have all the common behaviour in. If you really want to use them class specific, then, yes, you should do the cast. But I feel like it kills the purpose of abstract factory.
if you want a specific product or group of products when subclass your factory and receive it from the child factory
Upvotes: 0
Reputation: 7388
You could explicitely cast the return value to Subclass
which will fail as soon as the factory returns another Subclass
of Superclass
and will throw an exception during runtime. Therefore, don't do it.
The more appropriate way would be to declare myObj
as type Superclass
and have the interface contain the methods you need. If you need to know the exact subtype that is returned, using a factory pattern is a bit pointless.
Upvotes: 1
Reputation: 52789
As the method returns Superclass you cant directly assign it to a Subclass.
You need to use this or type cast.
Superclass myObj = ProbeFactory.createProbe("type1");
Subclass myObj = (Subclass) ProbeFactory.createProbe("type1");
Upvotes: 0
Reputation: 9380
It's the other way around. If you get a SubClass
you can assign it to a SuperClass
variable (if we assume SubClass extends SuperClass).
Upvotes: 0
Reputation: 421040
The error says that it cannot convert from Superclass to Subclass
That's right. It's the same reason you can't store a Number
in an Integer
for instance (The Number
could actually be a Double
!)
If you know that Subclass
is returned from ProbeFactory.createProbe("type1")
then you can cast it like this:
Subclass myObj = (Subclass) ProbeFactory.createProbe("type1");
Down-casting should be avoided if possible. Either you design it so that you can do with
Superclass myObj = ProbeFactory.createProbe("type1");
or you could try to create a type-safe version of the factory:
Subclass myObj = ProbeFactory.createSubProbe("type1");
Upvotes: 2