0

I have a superclass called BaseClass which has a table called children in which it should have subclasses of BaseClass, How would I make a table like that and make a method that returns that table? Also how should I be storing that table in the other classes that are requesting it? Here is my current code:

public class BaseClass<T> {
    // // //  Private Variables  // // //
    
    private int ParentChildID;
    private int NextChildID = 0;
    private BaseClass Parent;
    private BaseClass[] children;
    
    
    // // //  Public Variables  // // //
    
    public String Name = "BaseClass";
    public String ClassName = "BaseClass";
    
    
    // // //  Private Methods  // // //
    
    private void destroyChild(int ChildID) {
        children[ChildID] = null;
    }
    
    private void addChild(BaseClass Child) {
        children[NextChildID] = Child;
        Child.Parent = this;
        NextChildID++;
    }
    
    
    // // //  Public Methods  // // //
    
    public void destroy() {
        if (Parent != null) {
            Parent.destroyChild(ParentChildID);
        }
    }
    
    public void clearAllChildren() {
        for (int i = 0; i < children.length; i++) {
            children[i] = null;
        }
    }
    
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public BaseClass setParent(BaseClass Parent) {
        Parent.addChild(this);
        destroy();
        this.Parent = Parent;
        return this;
    }
    
    public BaseClass[] getChildren() {
        return children;
    }
}


rokoblox
  • 84
  • 9
  • You don't use `T` anywhere. – Dmytro Mitin Sep 16 '20 at 22:03
  • Not sure I entirely understand what you're going for, but if you're trying to track all instances of a class and it's subclasses then you could make `children` a static list and have the superclass add itself to that list with the constructor (maybe passing in a ID parameter). Then every subclass would have to call `super(someId);` and get collected into the list. – Tim Hunter Sep 16 '20 at 22:03
  • Note that you're initializing `children` at all so the array will be null. You might want to use a `List` instead and if you're after something like `BaseClass>` where `S` is a subclass hen use `List children = /*init to ArrayList or LinkedList*/;`. – Thomas Sep 16 '20 at 22:06
  • https://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java – Dmytro Mitin Sep 16 '20 at 22:53
  • `children` should be a list that could contain any object as long as it's a subclass of `BaseClass` – rokoblox Sep 17 '20 at 12:26

0 Answers0