0

G'day!

Given two classes: A and B, and given G: a generic class, in Java.

If I were to define the generic class as G<A> or G<B>, would it be make any difference that A and B are defined as classes themselves? My gut feel is no, because the letter is just the parameter to be used within the class attributes/methods, and will be replaced by whatever class G is parameterised by, upon initialisation. But this does seem to complicate things, because what if you wanted to have an attribute of type A or B within G?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
James Adams
  • 678
  • 4
  • 11
  • 21

2 Answers2

4

Generic type variables, like any other variables, have scope. Their scope is the body of the class they are declared in.

Within that class, the name they were defined with always refers to the generic type. If you have another type of the same name declared elsewhere, you'll need to use its fully qualified name.

class Generic<Integer> {
    Integer ourTypeVariable;
    java.lang.Integer realInteger;
}

Don't code like this, especially for common type names (everything in the JDK basically).

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Also, if you properly give classes more meaningful names you'll find this issue rarely comes up. – candied_orange Oct 27 '14 at 01:45
  • @CandiedOrange: True. But OTOH the JDK itself has multiple `Date`s and multiple `List`s :-) – Thilo Oct 27 '14 at 02:48
  • That's a different problem. Were talking about colliding generic type names with class names. That rarely happens. You're talking about class name collisions which is what namespaces/packages resolve. – candied_orange Oct 27 '14 at 02:52
2

Yes, this would work (but it is potentially confusing).

The following are equivalent

class G<A> {}
class G<B> {}
class G<T> {}
class G<String> {}

So I suggest you choose a placeholder name that reduces confusion.

But this does seem to complicate things, because what if you wanted to have an attribute of type A or B within G?

Again, you can avoid this by naming the placeholder something else.

But if you have to, you can disambiguate by fully qualified name:

class G<A>{
   my.com.package.A someVariable;
}
Thilo
  • 257,207
  • 101
  • 511
  • 656