This code has an error in it but I dont know how I can go about correcting it:
public class Point<T extends Number super Integer>{
}
This code has an error in it but I dont know how I can go about correcting it:
public class Point<T extends Number super Integer>{
}
public class Point<T extends Number>{
}
or this
public class Point<T extends Integer>{
}
You can't use super
like that. See here: java generics super keyword
Super is only valid with wildcards, not with named type parameters.
Let's imagine the compiler allowed that. There are only two types that can be said to extend Number and be a supertype of Integer, those are Number and Integer.
I'm struggling to see what benefit you would get in doing this rather than a straightforward non-generic Point type with int fields.
If the real case is more involved and you want a generic Point that could use Doubles, Integers etc., sure, use T extends Number if the Number restriction helps to avoid mistakes.
However, just having T extends Number does not give you access to +, -, *, etc. You might want the type class pattern for that, which involves having a separate dictionary of operations passed from the point where the generic type is created to where the numeric operations happen.
E.g.,
interface NumericOperations<T extends Number> {
T plus(T x, T y);
T subtract(T x, T y);
T multiply(T x, T y);
...
}
You would need to define instances of that type class, e.g., public static final NumericOperations intOperations = new NumericOper.....;
..and pass those instances around to get at plus, minus etc., within Point's methods.
You can only use the super
keyword with a wildcard.
You should take a look at the PECS principle : Provider Extends Consumer Super.
The super keyword is used in generics methods for consumer generic objects.
Example :
public void copyList(List<? extends Number> elementsToBeCopied,
List<? super Integer> listToBeFilled) {...}
Remark : Integer
is a final class and cannot be extended, so the extends
keyword is unnapplicable.
This article shows a good example of how super
and extends
can be used.