Java Question

Generic extending or generic that extends

I find this approach valid:

public class Test<T extends Number>{

as well as

public class Test<T> extends Number{

is there any good practice that am missing, since both approaches will give me the same result, only that the 2nd one forces me to implement the abstract methods.

public int intValue() {
throw new UnsupportedOperationException();

public long longValue() {
throw new UnsupportedOperationException();

public float floatValue() {
throw new UnsupportedOperationException();

public double doubleValue() {
throw new UnsupportedOperationException();


Answer Source

I find this approach valid... as well as...

Well, they're both valid Java.

since both approaches will give me the same result

No, they mean very different things.

Let's call the classes implementing the two approaches Test1 and Test2:

public class Test1<T extends Number> { ... }
public class Test2<T> extends Number { ... }

Test1<Integer> a1 = new Test1<>();  // OK.
Test2<Integer> a2 = new Test2<>();  // OK.

Test1<Object> b1 = new Test1<>();   // Compiler error: Object not in bounds.
Test2<Object> b2 = new Test2<>();   // OK - T isn't bounded.

Number c1 = new Test1<Integer>();   // Compiler error: a Test1 isn't a Number.
Number c2 = new Test2<Integer>();   // OK.

So, the two classes aren't equivalent.

The one you should choose depends upon what you're trying to achieve.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download