OOP Inheritance question
Is the following scenario possible:
- Create an object pool of
Animal开发者_如何学Python
, calledAnimalPool
- Allocate an
Animal
object (calledmyAnimal
) from theAnimalPool
- Cast
myAnimal
to aCat
- Set a
Cat
-specific field - Store
myAnimal
into an array ofAnimal
(say at index 0) - Later access the array, and cast index 0 to
Cat
and check the field I set in 4.
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. :-)
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
- another thing is that this is possible in another OO languages (with dynamic typing)
- consider using another pattern in this case
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.
精彩评论