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 ... , . , , . , - ?
:
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>
}
}
}