If one of the bounds is a class, it must be specified first in java generics. What for?

I meant this java docs . If one of the bounds is a class, it must be indicated first . I feel that this should be allowed in any order.

Why does java have such a limitation? Is there any specific reason for this?

Several borders

The previous example shows the use of a type parameter with single bound, but a type parameter can have several bounds:

A variable of a type with several restrictions is a subtype of all the types listed in the evaluation. If one of the boundaries is a class, it must be specified above. For instance:

Class A { /* ... */ } interface B { /* ... */ } interface C { /* ... */ } class D <T extends A & B & C> { /* ... */ } 

If the A binding is not specified first, you get a compile-time error:

  class D <T extends B & A & C> { /* ... */ } // compile-time error ,but why ? 
+4
source share
4 answers

First, there can only be one class; each Java class (except java.lang.Object , which is a special case as the root of the hierarchy) can inherit only one class from one class. There can be several interfaces, but no more than one class. This greatly simplifies the processing of the type hierarchy and the object construction process.

Given that the language developers decided that the class should be specified first within the boundaries (if it is present at all). Actually, there is no serious reason for this - the compiler could just cope with the restrictions for only one class without ordering - but this simplifies teaching, because there is a simple rule: if you use the class as a generic type, put it first.

+3
source

Perhaps they simply combine the interfaces together, separately from the class.

If T was a class, it would look like this:

 public class T extends A implements B, C { 

But in generics there are no implements and only extends . Thus, the restriction can only be to list the class itself first and then list the interfaces due to the lack of the implements keyword.

+1
source

JLS # 4.4. Type Variables

Each type variable declared as a type parameter has a binding. If no boundary is declared for the type variable, Object is assumed. If a border is declared, it consists of:

  • a variable of the same type T or
  • class or interface type T , possibly followed by interface types I1 & ... & In
0
source

I would say that "A type variable with multiple bounds is a subtype of all the types listed in the bound." , and it seems that Java asks you to specify extends First in the class declaration, which would be the reason. (On the other hand, a class can distribute only one class)

0
source

Source: https://habr.com/ru/post/1442686/


All Articles