public static <T extends String> void main(T[] args) { System.out.println("Hello World!"); }
I was curious to see if the above snippet of code would compile and run successfully, and it does! However, I also wondered what would happen if T extends String
was replaced with T extends String & AutoClosable
; String
does not implement AutoClosable
, so I didn't expect this to run successfully, but it still does!
public static <T extends String & AutoCloseable> void main(T[] args) { System.out.println("This still works!"); }
So my question is, why does this still run successfully?
Notes:
Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem.
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
Advantage of Java Generics 1) Type-safety: We can hold only a single type of objects in generics. It doesn?t allow to store other objects. Without Generics, we can store any type of objects. List list = new ArrayList();
Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.
This is because a type parameter has a bound:
<T extends String> => String <T extends String & AutoCloseable> => String & AutoCloseable
And the bytecode after erasure is the same as for the regular main
declaration in both cases:
public static main([Ljava/lang/String;)V
JLS §4.4. Type Variables:
The order of types in a bound is only significant in that the erasure of a type variable is determined by the first type in its bound, and that a class type or type variable may only appear in the first position.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With