I know that casting can really only be done from a sub class to a super class (up casting) but this example illustrates what I would like to do.
Class Super {}
Class Sub extends Super {}
Super super = new Super();
Sub sub = (Sub)super;
I believe this is referred to as “down” casting which is not allowed so…
What is the best way to create an object of type Sub given an object of type Super.
EDIT:
That’s the question – What’s the best way to convert an Animal to a Cat.
The answer? Start with a base type animal and copy the attributes to the cat. Add fur and a tail, etc. Basically a copy constructor. Is this the right answer (or a good answer)?
ANOTHER EDIT:
I think my question is pretty clear but maybe it is too general. Asking for the “best” way to do something tends to give a lot of varying responses. I realize the best way can be different in different circumstances.
I’m not looking for a tutorial on Java or OO basics. Just fishing for opinions so I can solve this problem as I have outlined it using best practices.
A
Catis anAnimal.If I give you an animal (doesn’t have to be cat), how would you convert it to a cat?
EDIT:
There’s a way to do almost anything. Most of the time, you shouldn’t. I believe a better design would eliminate the need for downcasting. But you can:
have a constructor in
Superthat takes aSubas parameter.implement a factory of
Superand have a method that takes aSubas parameter.I suggest that you expand your question, tell us exactly what you need, as I really think a more elegant solution exists.