Casting parent to child
in
Programming Questions
•
1 year ago
Hi,
looks like that it is imposible to cast parent type to child type in processing (and mayby in java in genral). Is that true?
This code
- class TIsoSurf {
- float R;
- PVector X;
- TIsoSurf (){ X = new PVector(); }
- TIsoSurf (float x, float y, float z, float R){ X = new PVector(); set(x,y,z,R); }
- final void set (float x, float y, float z, float R){ X.set(x,y,z); this.R=R; };
- }
- class TSphere extends TIsoSurf{}
- class TPlane extends TIsoSurf{}
- TSphere S = (TSphere) new TIsoSurf(0,0,0,99.9);
makes error
- CastChild$TIsoSurf cannot be cast to CastChild$TSphere
this discusion says that chasting parent to child should be possible (post
Saturday, January 08, 2011 02:40)
this is weird, because casting from "Object" for example when I use ArrayList is possible
- ArrayList L = new ArrayList();
- L.add( new TIsoSurf(0,0,0,99.9) );
- Object O = L.get(0);
- TIsoSurf S1 = (TIsoSurf)O;
- TSphere S2 = (TSphere)O;
there
TIsoSurf S1 = (TIsoSurf)O; is OK, but
TSphere S2 = (TSphere)O; makes and error. How the hell the compiler knows that the "Object" is
TIsoSurf and not
TSphere ????
Motivation:
I just want to use shared inheriated constructor from
TIsoSurf for all it's childs, I don't want to write it again and aragin for all the childs, if the data structure is the same.
1