Re: Overriding methods: difference between Java 1.4 and 5+ ?
Neo_it wrote:
This feature is introduce in J2SE 5.0, in which you can override the
method with the covariant return type. this covariant term is used in
J2SE 5.0 document. if i say in broad term then you can use any class
that is in class hierarchy.means any sup class or class specified in
return type. internally it do implicit type conversion for you.
Here's why it's allowed. Consider
public interface StatementCreator
{
java.sql.Statement createStatement() throws java.sql.SQLException;
}
and an implementing class with
public com.lewscanon.sql.Statement createStatement()
throws java.sql.SQLException
where the return type implements java.sql.Statement. From the point of view
of any interface-typed variable that invokes the method, it is getting a
java.sql.Statement back, so the contract is fulfilled. It's a natural
concomitant of implicit widening conversions. As long as what you want is
wider than what you got, you're fine.
The put side is the converse. What you want to put has to be narrower, so the
method signature of the callee has to be wider. This is "contravariant", or
supertype substitution, contrasted with the "covariant" or subtype
substitution in the return part of the method signature. This is where the
concept of method overloads and the rules for finding the narrowest available
signature, i.e., contravariant type pattern apply.
The terms "contravariant" and "covariant" are more common in the context of
generics, where the wildcard "? extends" is a covariant type, and "? super" is
the contravariant. You see the latter a lot in Comparables and the like:
public static <T extends Comparable<? super T>> void sort(List<T> list)
<http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List)>
public static <T> void sort(List<T> list, Comparator<? super T> c)
<http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)>
--
Lew