Reputation: 3106
Is the following scenario possible:
Animal
, called AnimalPool
Animal
object (called myAnimal
) from the AnimalPool
myAnimal
to a Cat
Cat
-specific fieldmyAnimal
into an array of Animal
(say at index 0)Cat
and check the field I set in 4.Upvotes: 0
Views: 264
Reputation: 8842
in Java when in point 2 you create Animal then in 3 you can't cast it to Cat
if
class Animal {
}
class Cat extends Animal {
private String mewTone;
public void setMewTone(String t){
this.mewTone = t;
}
}
you can have pool with Animal, but if you want to cast to Cat and use method setMewTone the given object have to be Cat. You can check it. For example:
Animal animal = objectPool.get();
if(animal instanceof Cat){
Cat castedToCat = (Cat)animal;
castedToCat.setMewTone("horrible");
} else {
System.out.println("This is not a cat.");
}
So when you run this:
ObjectPool<Animal> objectPool = new ObjectPool<Animal>();
objectPool.add(new Animal());
Animal animal = objectPool.get();
((Cat)animal).setMewTone("sth");
you will get java.lang.ClassCastException: Animal cannot be cast to Cat
Upvotes: 2
Reputation: 811
I think you can do what you're trying to do, just not EXACTLY the way you're thinking of doing it. Your AnimalPool is going to be essentially an Animal "factory" (look up factory pattern, it may help, but it's not the important part here.), AND double as a collection of "Animals". Make a "Animal" object, which has all the methods and properties common across all animals. Then make the animals you need such as "Cat" and "Dog" and derive them from the base class of "Animal". Then in your "AnimalPool", add functions to create and return specific types of Animal, such as getDog() and getCat(), or make one function with a parameter. Create that specific type with your AnimalPool factory, and because it derives from "Animal", you can add it to a list of type "Animal". When you retrieve Animals from the AnimalPool list, you will be able to cast them to their appropriate types. Depending on the reflection capabilities of your language, you may even be able to get the object to tell you what type it is.
This is just simple case of using inheritance and a factory pattern. Look those two things up, and I think you'll be on easy street with what you're trying to accomplish. Good luck, and hope it helps. I can give you a code sample if you need it. :-)
Upvotes: 2
Reputation: 10005
Why would you cast the object second time at point 6? Anyway it will be of type Cat so no need to do that. And yes the field will be set.
Upvotes: 1