Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic programming in java

Tags:

java

generics

I have some confusion about generic programming in java:

If Manager is subclass of Employee,

Collection<Manager> managers=new Collection<Manager>;  
Collection<Employee> employees=managers;//why illegal?

Why the last statement is illegal?

Since according to illustration in the book CORE JAVA,after the erasion,Collection<Manager> and Collection<Employee> are all converted into raw type Collection.

like image 730
e.b.white Avatar asked Aug 04 '26 03:08

e.b.white


2 Answers

If the above were true, then you could take your collection of managers, treat it as a collection of employees, and then put any employee into a collection of managers (i.e. not just a manager, but a (say) graduate trainee, a CIO etc.)

It's a little counter-intuitive. An orange is a fruit. A list of oranges is not a list of fruit (otherwise you could put an apple in it). There's a concise explanation in the Java Generics Tutorial.

like image 95
Brian Agnew Avatar answered Aug 05 '26 18:08

Brian Agnew


This is called covariance and contravariance. The issue you just discovered is a traditional problem of type systems. The corresponding wikipedia page discusses this issue in Java. It's worth taking some time to understand these issues correctly has it also relates also to method overriding (since JDK5, you can indeed change the return type of an overriden method as long as it's covariant).

like image 27
ewernli Avatar answered Aug 05 '26 17:08

ewernli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!