1

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>{
}
artbristol
  • 32,010
  • 5
  • 70
  • 103
Chaz32621
  • 127
  • 1
  • 12
  • Its a find the error problem for my java homework: FindTheError.java:2: expected public class Point{ – Chaz32621 Sep 28 '12 at 13:31
  • Before someone even says it, the [tag:homework] tag [is officially deprecated](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated), so please do not edit this question to have the [tag:homework] tag. – Brian Sep 28 '12 at 13:35

3 Answers3

1
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

Community
  • 1
  • 1
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
1

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.

Ricky Clarkson
  • 2,909
  • 1
  • 19
  • 21
1

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.

Samy Amirou
  • 191
  • 1
  • 2