Roedy Green coughed up:
On Fri, 15 Jul 2005 16:13:51 GMT, "Thomas G. Marshall"
IS this something general, a method can override with a different type
so long as the type is a subtype? The object still fulfills the
contract of the original base, but even more strictly.
http://java.sun.com/developer/JDCTechTips/2005/tt0104.html#2
Take my example, but modify the clone to return a simple string. Now the
clone() method is returning something that is a subtype of Object (the
return type used in Object.clone()). Note that it does not have to be a
subtype of Thing. This works, though is a little silly:
public class Clone2
{
public static class Thing implements Cloneable
{
public String clone()
{
return "hello";
}
}
public static void main(String[] args)
{
Thing thing = new Thing();
System.out.println(thing.clone());
}
}
So let's make a Thing and a sub-Thing (a Car):
public class Clone3
{
public static class Thing
{
public List method()
{
return new LinkedList();
}
}
public static class Car extends Thing
{
public ArrayList method()
{
return new ArrayList();
}
}
public static void main(String[] args)
{
Car car = new Car();
System.out.println(car.method());
}
}
This works because the (Car).method() returns an ArrayList, a sub-type of
List.
If I modify this to return some non-sub type:
public class Clone4
{
public static class Thing
{
public List method()
{
return new LinkedList();
}
}
public static class Car extends Thing
{
public String method()
{
return "hello";
}
}
public static void main(String[] args)
{
Car car = new Car();
System.out.println(car.method());
}
}
I get this (same as from 1.4) error message:
$ com Clone4.java
javac 1.5.0-beta2
Clone4.java:22: method() in experiments.simple.Clone4.Car cannot override
method
() in experiments.simple.Clone4.Thing; attempting to use incompatible return
typ
e
found : java.lang.String
required: java.util.List
public String method()
^
1 error