I have a object hierarchy like this A ^ | | B ^ | | C when I am doing a population of data, I am getting either object A or B. but I need a C object, with all the fields set to whatever is correct. when I do a upward casting from A to C that fails. how do I get a C object from A? Is there any best practices??? Is inheritance only good for narrowing casting (child in place of father) operation, what's the good way for widening operations (father in place of child)??? any help would be appreciated??? rgds Avijeet
Desai Sandeep
Ranch Hand
Joined: Apr 02, 2001
Posts: 1157
posted
0
Hi Avijeet, Looking at the object hierarchy, we can infer that reference of A can hold objects of A,B and C.This means any of the subtypes (B or C) can be upcasted to A.This is one interpretation of inheritance. You may also infer that downcasting a supertype may be allowed by inheritance.Consider the following code: <pre> A a = new A(); B b = new B(); C c = new C(); a = b; //This is what we usually do - upcasting! B b1 = (B)a; //This is what we are not used to - downcasting! </pre> The above code means that the reference of Class A should hold object of type B or type C, otherwise this downcasting will fail. I donot tend to use this quite often.Also,it doesn't look very elegant! Hope this helps, Sandeep
<b>Sandeep</b> <br /> <br /><b>Sun Certified Programmer for Java 2 Platform</b><br /> <br /><b>Oracle Certified Solution Developer - JDeveloper</b><br /><b>-- Oracle JDeveloper Rel. 3.0 - Develop Database Applications with Java </b><br /><b>-- Object-Oriented Analysis and Design with UML</b><br /> <br /><b>Oracle Certified Enterprise Developer - Oracle Internet Platform</b><br /><b>-- Enterprise Connectivity with J2EE </b><br /><b>-- Enterprise Development on the Oracle Internet Platform </b>
Avijeet Dash
Ranch Hand
Joined: Jan 21, 2001
Posts: 148
posted
0
hi, don't teach me casting or inheritance. tell me what is the best practice when u need a widening/downcasting ?
Junilu Lacar
Ranch Hand
Joined: Feb 26, 2001
Posts: 3008
posted
0
The only thing I can think of off the top of my head is to write constructors for C and B that takes an A as a parameter. Each constructor will dig in to the object passed and extract the necessary information, kind of like selective cloning. <pre> class A { ... }
class B extends A { public B(A a) { this.attrib1 = a.attrib1; this.attrib2 = a.attrib2; ... } } class C extends B { public C(A a) { super(a); ... } } // that way, you can have this code: A a = new A(); C c = new C(a); // c will be a "clone" of a </pre> [This message has been edited by JUNILU LACAR (edited June 27, 2001).]
Hello Avijeet, But why would you like to downcast? It violates the basic java architecture forget about best practices. Why don't you use composition if you need an instance of A in C. Jaydeep