1

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
    }
}

I.e. 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

2 Answers 2

6

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>();)

Sign up to request clarification or add additional context in comments.

2 Comments

Of couse can you have static member with generic parameters: public static <T> void method(T parameter) { ... }
@Oliver: but that's a generica parameter for that particular method, not for the class.
2

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.

3 Comments

You can assign any parameterisation of Node<> to that non-variable variable.
If I use it as a return from a method e.g. private Node<SomeType> search(Object o){.....return NOT_FOUND} Type mismatch: cannot convert from MyGenericClass.Node<capture#2-of ?> to MyGenericClass.Node<SomeType>. I have to explicitely cast
@user384706: That leaves the option of using the raw type Node, which will result in unchecked warnings. I'm afraid there is really no entirely clean way of doing this, as it goes against the type system, and the only reason it can work at all is that the value is null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.