I have an abstract class Dog
and multiple subclasses (Beagle
, Labrador
, Bulldog
...) extendig it. I have a DogHouse
that can store a Dog
.
My problem is that when I put for example a Beagle
into a DogHouse
like doghouse.addDog(beagle)
and then take it out with doghouse.getDog()
, this method gives me the beagle as a Dog
, but I want to get my Beagle
back.
DogHouse
has many more methods, they all give me Dogs
, but I work with specific dogs in my application. Does it mean that I always have to downcast?
Update:
I'm using TypeScript and can change any part of the code so my options are practically endless. What I don't understand:
Imagine you have two dog schools. Knowing that different breeds of dogs are capable of very different things and need different care and training, dog school 1 is specialized in Greyhound
s, while the other is training let's say Bulldog
s only.
There is a company selling DogHouse
s. They say that their product is compatible with any kind of Dog
, so both dog schools decide to buy from them.
A trainer at dog school 1 tells a Greyhound to run very fast: greyhound.runVeryFast();
- something that only greyhounds can do. It works.
Then, she sends the greyhound into a DogHouse: doghouse.addDog(greyhound);
- which works too.
After the dog could rest enough, she calls him and tells him to run very fast again: doghouse.getDog().runVeryFast();
- It does not work.
She turns to the company selling the DogHouse
s to complain what a stupid house they've built that a dog forgets in it to which breed he belongs. "Why do I have to tell the dog (cast him) that he is a Greyhound
every time he comes out of his house?"
The company answers "Sorry madam, maybe we can build a new house using generics." But then the lady answers: "And will it then accept Cat
s" too? I only want a house for Dog
s."
So my question is: How to build a proper DogHouse
?