I'm trying to instantiate a public non-static inner class but I keep getting a compilation error.
I have 2 classes: a tree class and a main class.
I'm ultimately trying to instantiate an array of points, but for the sake of this question, I'm trying to just instantiate a Point object.
The compilation error says that
Point can't be resolved to a type
What am I doing wrong?
Tree.java
public class Tree<T> {
public class Point<T> {
public T position[];
}
}
Main.java
public class Main {
public static void main(String args[]) {
Point<Double> point = new Tree<Point<Double>>().new Point<Double>();
}
}
Just leave out the T parameter when declaring the inner class.
Just use T inside, but don't try to redefine a type parameter with the same name T.
As suggested in the comments:
Tree<Double>.Point<Double> point = new Tree<Double>().new Point<Double>();
but it looks like a little bit too redundant don't you think?
you can remove the generic part of point
public class Tree<T> {
public class Point {
public T position[];
}
}
Tree<Double>.Point point = new Tree<Double>().new Point();
I suspect you don't want to have two different type parameters for Tree
and Point
. The way you wrote it, the T
of Point
shades the T
of Tree
, so the parameters are actually different. If you want them to be the same, remove the T
of the inner class. This way the T
of outer class can be used in the inner class as well.
public class Tree<T> {
public class Point {
public T position[];
}
public static void main(String args[]) {
Tree<Double>.Point point = new Tree<Double>().new Point();
}
}
If you really want to have two different T
s, you can instantiate a Point
like this. But then I highly recommend to rename one of the type parameters to prevent confusion.
Tree<Object>.Point<Double> point = new Tree<>().new Point<>();
Edit : According to the comments:
Tree<Tree<?>.Point<Double>>.Point<Double> point = new Tree<Tree<?>.Point<Double>>().new Point<>();
Edit : According to further comments
Since you want a Tree
to contain always Points, there is no use in using generics here. It is a little bit dependent on what you want to do with this class, whether to remove the type parameter of Tree
of the one of Point
.
Possibility 1 removing type parameter of Tree
public class Tree {
public class Point<T> {
public T position[];
}
}
You can go with that if you want to return a Point
from the methods in the Tree
Possibility 2 removing type parameter of Point
public class Tree<T> {
public class Point {
public T position[];
}
}
You should go with that if you want the methods in Tree
to return objects of type T
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.