Which methods compile?
A)
public List〈? super IOException〉 getListSuper() {
return new ArrayList〈Exception〉 ();
}
B)
public List〈? super IOException〉 getListSuper() {
return new ArrayList〈FileNotFoundException〉 ();
}
C)
public List〈? extends IOException〉 getListExtends() {
return new ArrayList〈Exception〉 ();
}
D)
public List〈? extends IOException〉 getListExtends() {
return new ArrayList〈FileNotFoundException〉 ();
}
#java #certificationquestion #ocp
https://www.udemy.com/course/ocp-oracle-certified-professional-java-developer-prep/?referralCode=54114F9AD41F127CB99A
A)
This method compiles because Exception is a super of IOException, and the list can contain IOException and its superclasses.
D)
This method compiles because FileNotFoundException is a subclass of IOException, and the list can contain IOException and subclasses of IOException.
Methods A) and C) will not compile because they attempt to return a list with a type that is not compatible with the bounded wildcard.
In A), Exception is not a subclass of IOException, and in C), Exception is not a subclass of IOException either.
The wildcard bounds must be respected for the code to compile.
Bounded types in Java generics allow you to specify constraints on the types that can be used with a generic class or method.
They are denoted by 〈? extends Type〉 for upper bounds (Type and subclasses of Type) and 〈? super Type〉 for lower bounds (Type and superclasses of Type).
This ensures type safety and flexibility in your code.