Question

I had been reading up on Generics in Java. In the Wildcard section in the tutorial below all examples are for parameterized methods. It got me thinking of why is there no example for wildcard parameterized type declaration. http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html

Does this make sense? What does it mean?

public class MyClass<?>{
    ? myVar;
}
Was it helpful?

Solution 2

Imagine B as subclass of A, i.e.:

public class A {}

public class B extends A {}

So, the following code is legal:

A a = new A();
A b = new B();

But, you can not cast parameterized types even of the same generic class and even if their type arguments are in "is a" relationship, i.e. the code below is illegal:

MyClass<A> aClass = new MyClass<A>();
MyClass<A> bClass = new MyClass<B>(); //compile error

(see Oracle Generics Tutorial for a more detailed description about "is a" relationship between parametrized types)

So in this case you should use wildcards:

MyClass<?> aClass = new MyClass<A>();
MyClass<?> bClass = new MyClass<B>();

or upper bounded wildcards:

MyClass<? extends A> aClass = new MyClass<A>();
MyClass<? extends A> bClass = new MyClass<B>();

In case of non-generic objects no wildcards are needed. You always can use Object (or other upper bound) and cast values of unknown types to it.

Regarding your example, it is not make sense. MyClass<?> is a parameterized type, i.e. is a concrete type created by passing type argument ?, but it is not a declaration of a generic class (see generic type invocation). Declaration should be like this:

public class MyClass<T> {
    T myVar;
}

So T is a type parameter, whereas wildcard (or a concrete type) is a type argument.

OTHER TIPS

With generics, you'd just do:

public class MyClass<T>{
    T myVar;
}

The ? syntax is used primarily when you want to give more context -- ie ? exteds SomeType

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top