but expected...">

Java -Accessing parent object using generics?

With the code below, I get a compilation error of "Incompatible types - found Tree<T>but expected Tree<T>." Any idea what I am doing wrong with generics? Any other way to access the parent of an object other than ParentObjectClass.this? I know of “workarounds,” for example adding a variable to a Node class that points to its parent. In addition, I could pass myInt as a constructor parameter, but I would like to find a more pleasant solution. Thanks for any suggestions.

I came across a similar question on this site, but I tried it for my code and couldn’t get it to work: Access "his" from an anonymous Java class .

public class Tree<T> implements TreeIF<T> {
    private int myInt;
    Node<T> root;

    ...

    // a constructor
    public Tree(Node<T> root) {
        this(root.getTree().getMyInt()); // call to different constructor
        this.root = root;
    }

    ...

    // a method
    public int getMyInt() {
        return myInt;
    }

    ...

    // inner class
    class Node<T> {
        T element;

        ...

        Tree<T> getTree() {
            // return Tree.this;     // I tried this too, but it didn't work
            **return Tree<T>.this;** // HERE THE COMPILE ERROR
        }
    }
}

, . , , , T , Node. , . Tree , Node, . . Tree , ( ) T , , T. E ... , . , , . , - ?

+3
2

, T. :

class Node<T>

:

class Node<E>

. , :

class Node

, T node T , ? , () Tree<String>.Node - Tree<String>.Node<Object>.

+5

:

public class Tree<T> {
    private int myInt;
    Node root;

    ...

    // a constructor
    public Tree(Node root) {
        this(root.getTree().getMyInt()); // call to different constructor
        this.root = root;
    }

    ...

    // a method
    public int getMyInt() {
        return myInt;
    }

    ...

    // inner class
    class Node {
        T element;

        Tree<T> getTree() {
            return Tree.this; // leave out <T>
        }
    }
}
0

All Articles