Search code examples
javainitializationsubclasssuperclassextends

java, initialize SubClass from SuperClass


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


Solution

  • If you have a List<Base>, then you cannot convert it to a List<SubClass>. This is mainly because the list may not contain instances of SubClass. The best you can do is:

    List<SubClass> newList = new List<SubClass>();
    for(Base b: list){
        if (b instanceof SubClass) {
            SubClass sub = (SubClass)b;
            . . .
            newList.add(sub);
        }
    }
    

    Generally, however, when you find yourself doing this kind of thing, there's something wrong with your design. You might want to avoid subclassing Base and using composition instead.

    EDIT Based on your comments, it sounds like you want to construct a list of SubClass instances using a list of Base instances as a start. One approach is to define a constructor for SubClass that takes a Base as an argument.

    public class SubClass extends Base{
        private boolean selected;
    
        public SubClass() {
            // default constructor
        }
    
        public SubClass(Base original) {
            // copy constructor -- initialize some fields from
            // values in original, others with default values
        }
        ...
        getter und setter
        ...
    }
    

    Then you can construct your new list with:

    List<SubClass> newList = new List<SubClass>();
    for(Base b: list){
        SubClass sub = new SubClass(b);
        . . .
        newList.add(sub);
    }