Java 5 added covariant return types , which means an overridden method in a derived class can return a type derived from the type returned by the base-class method:
// polymorphism/CovariantReturn.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
class Grain {
@Override
public String toString() {
return "Grain";
}
}
class Wheat extends Grain {
@Override
public String toString() {
return "Wheat";
}
}
class Mill {
Grain process() {
return new Grain();
}
}
class WheatMill extends Mill {
@Override
Wheat process() {
return new Wheat();
}
}
public class CovariantReturn {
public static void main(String[] args) {
Mill m = new Mill();
Grain g = m.process();
System.out.println(g);
m = new WheatMill();// in Java, every cast is checked
g = m.process();
System.out.println(g);
}
}
/* Output:
Grain
Wheat
*/
The key difference here is that pre-Java-5 versions forced the overridden version of process() to return Grain , rather than Wheat , even though Wheat is derived from Grain and thus is still a legitimate return type.
Q1: use
javac -target 1.4 polymorphism/CovariantReturn.java
prompt:
javac: target release 1.4 conflicts with default source release 1.8
A1: use
javac -source 1.4 -target 1.4 polymorphism/CovariantReturn.java
works for me. but it prompt the following:
warning: [options] bootstrap class path not set in conjunction with -source 1.4
warning: [options] source value 1.4 is obsolete and will be removed in a future release
warning: [options] target value 1.4 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
polymorphism/CovariantReturn.java:7: error: annotations are not supported in -source 1.4
@Override
^
(use -source 5 or higher to enable annotations)
1 error
4 warnings
remove @Override, it prompt:
warning: [options] bootstrap class path not set in conjunction with -source 1.4
warning: [options] source value 1.4 is obsolete and will be removed in a future release
warning: [options] target value 1.4 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
polymorphism/CovariantReturn.java:25: error: process() in WheatMill cannot override process() in Mill
Wheat process() {
^
return type Wheat is not compatible with Grain
1 error
4 warnings
The result verified the previous conclusion.
referecnes:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/polymorphism/CovariantReturn.java