Question

What is the hierarchy of extends? For example, things like Number, integer, and so on.

For example,

public class Foo<extends Integer>
{.....}

What types would this accept?

What is the highest type in the class? What is the lowest type in the class?

Was it helpful?

Solution

If you were to complete the generic declaration, then what you would have is a upper-bounded generic type.

 public class Foo<T extends Integer> { }

Here, T is bound to be anything that either is or extends from an Integer. But, since Integer is a final class...it'd only be able to hold Integer.

So, a declaration like these are compile-time legal and enforced:

Foo<Integer> foo = new Foo<>();
Foo bar = new Foo(); // This will produce raw type warnings!

...whereas a declaration like this isn't compile-time legal, since the bound is that it must either be or extend Integer.

Foo<Long> baz = new Foo<>();

Formally, the compiler will show you this:

 Error:(17, 56) java: cannot infer type arguments for Foo<>;
 reason: no instance(s) of type variable(s) T exist so that Foo<T> conforms to Foo<java.lang.Long>

If you went higher in Integer's hierarchy, you'd arrive at Number, which would allow you to instantiate with any class that extended Number:

public class Foo<T extends Number> { }

Then, the Long generic type would be legal, and your permissible types would be these:

  • Number
  • Short
  • Integer
  • Double
  • Float
  • Byte
  • BigDecimal
  • BigInteger

...just to name a few.

OTHER TIPS

It would accept anything that is the specified class, or a potential subclass of it.

So if I did:

<? extends MyClass>

It would allow types "MyClass", and say another class that was public class Another extends MyClass. But it wouldn't accept other classes.

Do you mean

public class Foo <T extends Integer>{.....}

?

T is going to accept anything that is-an Integer.

I don't understand what is the "highest" and "lowest" type you mean here. However the above statement should be clear enough I believe.

e.g. You cannot pass in Number (which is the parent class of Integer). You can pass in Integer. If you have a FooInteger that extends Integer, you can use it here too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top