Reputation: 9
I'm trying to pass a subclass object to a method that has a superclass parameter so I only have to make one of that method. I have conditional statements like "if (subclassObject instanceOf CertainSubClass)" so it can tell which subclass the object came from.
The problem is once the object is passed to the parameter the program seems to only recognize it as a superclass object. Then I can't add it to an ArrayList of the type ArrayList<CertainSubClass>
.
What exactly happens to the subclass object when it's passed to a method with a superclass parameter? And how could I get around this problem? I'd rather not make 3 methods for the 3 subclasses I have. Thanks
Upvotes: 0
Views: 235
Reputation: 18408
"I'd rather not make 3 methods for the 3 subclasses I have."
But if your process is different for each case (and your instanceof checks will make it so) then you HAVE 3 distinct methods, semantically. Bundling them in one method just for the purpose of saving some method declarations is a poor idea.
Upvotes: 1