Rules for covariant returns???

J

Joost Kraaijeveld

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
 
N

NullBock

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.
 
N

NullBock

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.
 
R

Roedy Green

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top