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 can try to convert the super class variable to the sub class type by simply using the cast operator. But, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator.
In java object typecasting one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its subclass or superclass types or interfaces.
Downcasting: Similarly, downcasting means the typecasting of a parent object to a child object.
In Java, the object can also be typecasted like the datatypes. Parent and Child objects are two types of objects. So, there are two types of typecasting possible for an object, i.e., Parent to Child and Child to Parent or can say Upcasting and Downcasting. In Java, the object can also be typecasted like the datatypes.
You can only downcast if the actual object is of the type "Sub". For example:
Super subAsSuper = new Sub();
Sub sub = (Sub)subAsSuper
Your way won't work because super isn't a subclass of sub. So you'll get a Runtime error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With