Content deleted Content added
MOS:HEAD |
m Task 70: Update syntaxhighlight tags - remove use of deprecated <source> tags |
||
Line 11:
In the body of a generic unit, the (formal) type parameter is handled like its [[bounded quantification|upper bound]] (expressed with <code>'''extends'''</code>; <code>Object</code> if not constrained). If the return type of a method is the type parameter, the result (e.g. of type <code>?</code>) can be referenced by a variable of the type of the upper bound (or <code>Object</code>). In the other direction, the wildcard fits no other type, not even <code>Object</code>: If <code>?</code> has been applied as the formal type parameter of a method, no actual parameters can be passed to it. However, objects of the unknown type can be read from the generic object and assigned to a variable of a supertype of the upperbound.
<
class Generic <T extends UpperBound> {
private T t;
Line 28:
wildcardReference.write(new UpperBound()); // type error
concreteTypeReference.write(new UpperBound()); // OK
</syntaxhighlight>
== Bounded wildcards ==
Line 57:
Upper bounds are specified using <code>extends</code>:
A <code>List<? extends MyClass></code> is a list of objects of some subclass of <code>MyClass</code>, i.e. any object in the list is guaranteed to be of type <code>MyClass</code>, so one can iterate over it using a variable of type <code>MyClass</code><ref>[[Inheritance (object-oriented programming)]]</ref>
<
public void doSomething(List<? extends MyClass> list) {
for (MyClass object : list) { // OK
Line 63:
}
}
</syntaxhighlight>
However, it is not guaranteed that one can add any object of type <code>MyClass</code> to that list:
<
public void doSomething(List<? extends MyClass> list) {
MyClass m = new MyClass();
list.add(m); // Compile error
}
</syntaxhighlight>
The converse is true for lower bounds, which are specified using <code>super</code>:
A <code>List<? super MyClass></code> is a list of objects of some superclass of <code>MyClass</code>, i.e. the list is guaranteed to be able to contain any object of type <code>MyClass</code>, so one can add any object of type <code>MyClass</code>:
<
public void doSomething(List<? super MyClass> list) {
MyClass m = new MyClass();
list.add(m); // OK
}
</syntaxhighlight>
However, it is not guaranteed that one can iterate over that list using a variable of type <code>MyClass</code>:
<
public void doSomething(List<? super MyClass> list) {
for (MyClass object : list) { // Compile error
Line 87:
}
}
</syntaxhighlight>
In order to be able to do both add objects of type <code>MyClass</code> to the list and iterate over it using a variable of type <code>MyClass</code>, a <code>List<MyClass></code> is needed, which is the only type of <code>List</code> that is both <code>List<? extends MyClass></code> and <code>List<? super MyClass></code>.<ref>[[Java syntax|Java syntax(Generics)]]</ref>
|