I am confused on the following:
I want to do:
public class MyGenericClass<SomeType> extends SomeMoreAbstractClass<SomeType>{
private Node<SomeType> beginNode;
private static final Node<SomeType> NOT_FOUND = null;
private static class Node<SomeType>{
//class definition here
}
}
Ie I want to use the NOT_FOUND
in the code in checks for null
I get the error Cannot make a static reference to the non-static type AnyType
in the line that I declare private static final Node<SomeType> NOT_FOUND = null;
How can I get arround this? I prefer to use it as a class variable and not an instance variable
You need to remove the static
modifiers. Generics are, by definition, coupled to the concrete object. It is not possible to have static
(= identical for all objects) members, that have a generic parameter.
Don't forget that SomeType
is just a placeholder for what ever class you use, when you instanciate the object. (like this: MyGenericClass<Integer> x = new MyGenericClass<Integer>();
)
Simply declare the field as
private static final Node<?> NOT_FOUND = null;
As it's static, it will be shared between all instances of MyGenericClass
, so it can't refer to SomeType
which is a type parameter specified per class instance. Node<?>
makes it compatible with all possible type parameters. It is then not useful for anything that depends on a specific type parameter, but fortunately, comparison with null
still works.
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.