Hi,
Is there any documentation about the rules concerning the covariant
return of a function?
Can I return an abstract class?
Can I return an interface?
TIA
Joost
NullBock - 29 Nov 2005 16:07 GMT
A variable defined as an interface or a class (whether abstract or not)
can reference any object instantiated from that class, or a descendant
thereof.
Hashtable = new Properties();//no problem.
Functions work exactly the same. Consider a method in the Collections
class:
List synchronizedList(List list)
List is an interface. Any object might be returned, with the sole
stipulation that it implements the LIst interface.
Walter Gildersleeve
Freiburg, Germany
______________________________________________________
http://linkfrog.net
URL Shortening
Free and easy, small and green.
NullBock - 29 Nov 2005 16:24 GMT
They fall under the same rules as for other methods :
interface Base {
public Map func();
}
interface Derived extends Base {
public SortedMap func();
}
That is perfectly legal. Your derived class's covariant method simply
can't break the contract of the overridden class/interface, ie, it can
only return something as restrictive or more restrictive as the base
class.
Walter Gildersleeve
Freiburg, Germany
______________________________________________________
http://linkfrog.net
URL Shortening
Free and easy, small and green.
Roedy Green - 29 Nov 2005 17:39 GMT
On Tue, 29 Nov 2005 16:58:19 +0100, Joost Kraaijeveld
<J.Kraaijeveld@Askesis.nl> wrote, quoted or indirectly quoted someone
who said :
>Can I return an abstract class?
>Can I return an interface?
yes. All you need is for the object you return to extend that
abstract class or implement that interface. Sun does this sort of
thing all the time.
Have a look at URL.openConnection which nominally returns an
URLConnection but actually returns an HttpURLConnection for http:
urls.

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.