How to handle feeder and inheritance in Java

I would like the "children" field to contain a list of objects with the type of the containing object. However, when inherited, I get errors due to downcasting. What strategies can I use to maintain the hierarchy, but have access to the child objects appropriately?

public class Node<T>{

    protected T value;
    protected Node<T> parent;
    private ArrayList<Node<T>> children;

    public Node(T value){
        this.value = value;
        this.children = new ArrayList<Node<T>>();
    }

    public ArrayList<Node<T>> getChildren(){
        return this.children;
    }

    //...other methods...//

}

When I try to call getChildren () in this class, I get a "type mismatch" error because it is trying to compress.

public class DecidableTree<T extends Decidable<T>> extends Node<T>{

    public DecidableTree(T value) {
        super(value);
    }

    public randomInvolvedFunction(){
        //...other code...//
        for(DecidableTree<T> child : this.getChildren()){
            child.decidableTreeSpecificMethod();
        }
        //...other code...//
    }

    //...other methods...//

}

Unfortunately, I cannot just override the getChildren () function because the return types must match.

+4
source share
1 answer

Problem

, , , , Node DecidableTree. , DecidableTree Node, Node, .

, , , instanceOf, .

, Node . V , Node, T Node.

,

public abstract class Node<T, V> {
    protected V value;
    protected Node<T,V> parent;
    private List<T> children;

    public Node(V value){
        this.value = value;
        this.children = new ArrayList<T>();
    }

    public List<T> getChildren(){
        return this.children;
    }

    public void addChild(T child){
        this.children.add(child);
    }

    public V getVal(){
        return this.value;
    }
}

Node T , , , . , , DecidableTree , ,

public class DecidableTree<V> extends Node<DecidableTree<V>, V> {

    public DecidableTree(V value) {
        super(value);
    }

    public void randomInvolvedFunction(){
        for(DecidableTree<V> child : this.getChildren()){
            System.out.println(child.getVal());
        }
    }
}

DecidableTree - , T. , a T . .

, . . , .

Node , ArrayList - List , , . , Node , abstract. ArrayList, , List, ( - ). , .

+11

All Articles