Link to home
Start Free TrialLog in
Avatar of slickdeals

asked on

Covariants are allowed in Java 5 ... Please explain this phylosophy well?

Covariants are allowed in Java 5.  So an overridden method (marked @Override) will compile if the return type is a subclass of the super method's return type.  Considering this, why is it not legal to override a method with an argument that is a subclass of the super method's argument?

Please explain ... I have scratched my head to understand the same.
Avatar of CPColin
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of slickdeals


Then explain me this:

Allowing a subclass of the declared superclass imposes no more constraint on a method than its return type.  Why would it be wrong to pass a hashset in lieu of a collection?  You realize that this can be done using generics?  I mean why is it legal to define a method that looks like this:

public abstract void <T extends Collection> doSomething(T col)

and extend it like so:

public void  doSomething(HashSet set)
I punched in the code below and the compiler said I didn't properly implement the test method.

"HashSet" is still more specific than "T extends Collection."
public static abstract class Test1 {
   public abstract <T extends Collection<?>> void test(T arg);
public static class Test2 extends Test1 {
   public void test(HashSet<?> arg) {

Open in new window

Excellent opinion. If you can add more stuff it, that can help other people learning OO