• Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing subclass in the interface method  RSS feed

 
vivek ja
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an interface that has a method like this
public void method1(Object1 argObj1, Object2 argObj2)

In the class that implemtns this method
can i have

public void method1(Object1 argObj1, SubClassObject2 obj2)

where SubClassObj2 is the subclass of Object2?

I thought this is possible, but it gives me an error during compilation.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, when you override or implement a method you can make things less restrictive but not more restrictive. Anybody who sees this interface thinks he can pass the method an Object2 object. You can't change the rules and say, no it must be a subclass.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:
No, when you override or implement a method you can make things less restrictive but not more restrictive.


Stan meant to say that the declared argument types in your implementation must be exactly the same as in the interface -- modulo type parameters for generics in Tiger. You can make the exception specification "more restrictive" in the sense that you can declare fewer exceptions. You can also make the return type "more restrictive" in Tiger -- you can declare the method to return a subclass of what the interface method returns.
[ July 28, 2005: Message edited by: Ernest Friedman-Hill ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THanks for the correction. I think together we said: When overriding you can make arguments less restrictive, for implementing interfaces they must match exactly.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Stan]: I think together we said: When overriding you can make arguments less restrictive, for implementing interfaces they must match exactly.

No, the rule EFH gave is true for all overriding, whether the overridden method is in an interface or class. The argument types must match exactly or you're overloading, not overriding.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which, by the way, is specific to Java. Other languages allow what is called "contravariant argument types".

Java 5 introduced covariant return types. Contravariant argument types cannot be introduced without breaking existing code, because of necessary changes in the semantics of overloading, though.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!