I have been trying to generate a Factory supposed to return a different object of a common interface (say Item) according to the input parameter (I call it a context) of the function getItem(A context)
Now, assume I define a new type of context: B which inherits from A.
I wanted to return a different item depending on whether the object passed to the factory was of class B or A.
I tried to do as follows (overloading the method):
class Factory
{
static Item getItem(A context) {...}
static Item getItem(B context) {...}
}
This works fine if I do something like this:
B bContext=new B();
Item it=Factory.getItem(bContext);
However, if I cast an object to type A:
A bContext=(A) new B();
Item it=Factory.getItem(bContext);
the first factory method is called.
I thought that polymorphism would ensure the execution of the second method even after the cast, and I would like to know if I missed something?
I am aware that I could keep having a single method and use the is operator to check what the type of the variable is, but I thought the solution I presented above was a bit more elegant.