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.
You could add a constructor to the
Sub
class which takes aSuper
object as a parameter.You can only downcast if the actual object is of the type "Sub". For example:
Your way won't work because super isn't a subclass of sub. So you'll get a Runtime error.
A
Cat
is 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
Super
that takes aSub
as parameter.implement a factory of
Super
and have a method that takes aSub
as parameter.I suggest that you expand your question, tell us exactly what you need, as I really think a more elegant solution exists.
EDIT: From your question, it's not at all clear what you know and what you don't know. So don't be surprised when people answer the
part and not the (very vague) "actual question."
Yes, copying constructor is the way.
No, it's not the only one, factory method will do just fine.
No, it's not the best one — we have no idea what constraints and assumptions you have.
Old version: Casting can be done either way, with upcasting being usually unnecessary (unless you need to select a specific overloaded method).
There's generally no way to create an object of type Sub given an object of type Super other than creating a method which would construct a new object basing on the data from the given one.
In order to cast, you must be sure that the object you're casting is in fact of the type you cast to (or its subtype).
Take this idea in mind -
I did a very basic example here, but you can go where ever you want with this, you can make it work identically like inheritance. and it won't return any errors, whatsoever.