public class Base {
//long list of attributes
// no Constructor using fields
// no init methode
// i cannot change this class
}
now i extended the Base Class like:
public class subClass extends Base{
private boolean selected;
...
getter und setter
...
}
i become a list of Base object List<Base>
but i need the same list but as List<SubClass>
is there a way to initialize the Subclass from the Base Class?
example:
for(Base b: list){
SubClass sub = (SubClass)b; // Thats wrong i know
if(...){
sub.setSelected(true);
}
newList.add(sub);
}
i try to avoid the manual init of each Attribute of the Base Class
to the SubClass
i update my Question as requested in the Comments: the Design above is just an example. my QUESTIN EXACTLY IS:
why converting BaseClass into SubClass (sence Subclass extends BaseClass
) is not Possible? why Java dosn't allow me to do the following:
example:
Class Base{
private String name;
.....
}
Class SubClass extends Base{
private String title;
}
then
Base b = DBController.getById(...);
SubClass sub = (SubClass)b;
after that the Object sub
should have the Attribute Name from the Object b
and the title
Attribute is null
why is this not the case in java?
sorry for my bad english, thanks
List<Base>
field defined? In theBase
class itself? Do you have control over where its declared and how its initialized? – AffixationBase
objects. Remember that aSubClass
may be aBase
, but aBase
is not necessarily aSubClass
. You could hack the list, replacing eachBase
object with aSubClass
object, with its state cloned fromBase
, but that would be an ugly and bad thing to do. – Affixation