I have an abstract class
Dog and multiple subclasses (
Bulldog...) extendig it. I have a
DogHouse that can store a
My problem is that when I put for example a
Beagle into a
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
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?
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
Greyhounds, while the other is training let's say
There is a company selling
DogHouses. 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
DogHouses 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
Cats" too? I only want a house for
So my question is: How to build a proper