為了運(yùn)用多態(tài)性,當(dāng)編寫子類時(shí),你肯定會(huì)覆寫超類的方法。當(dāng)你覆寫超類的方法時(shí),你是否想到過更改方法的返回類型。如果你沒有,那祝賀你,你不曾為此煩惱過;如果你想到過,那你肯定是非常的郁悶。在Java 5.0以前,你是無法更改超類定義的方法的返回類型的。不過當(dāng)你使用Java 5.0以后,你會(huì)驚喜地發(fā)現(xiàn),此煩惱不復(fù)存在了。
下面的示例顯示了這一新特性的用法:
package
?com.jiang.tiger.chap1;


class
?Point2D?
{
??????
protected
?
int
?x,?y;


??????
public
?Point2D(?)?
{
????????
this
.x
=
0
;
????????
this
.y
=
0
;
??????}
??

??????
public
?Point2D(
int
?x,?
int
?y)?
{
????????
this
.x?
=
?x;
????????
this
.y?
=
?y;
??????}
??????

??????
public
?String?toString()?
{
??????????
return
?
"
the?position?is?x?=?
"
?
+
?x?
+
?
"
,y?=?
"
?
+
?y?;
??????}
????}
????
class
?Point3D?
extends
?Point2D?
{
??????
protected
?
int
?z;


??????
public
?Point3D(
int
?x,?
int
?y)?
{
????????
this
(x,?y,?
0
);
??????}
?

??????
public
?Point3D(
int
?x,?
int
?y,?
int
?z)?
{
????????
this
.x?
=
?x;
????????
this
.y?
=
?y;
????????
this
.z?
=
?z;?
??????}
??????

??????
public
?String?toString()?
{
??????????
return
?
"
the?position?is?x?=?
"
?
+
?x?
+
?
"
,y?=?
"
?
+
?y?
+
?
"
,z=?
"
?
+
?z;
??????}
????}
????
class
?Position2D?
{
??????Point2D?location;
?

??????
public
?Position2D(?)?
{
????????
this
.location?
=
?
new
?Point2D(?);
??????}
??????
public
?Position2D(
int
?x,?
int
?y)?
{
????????
this
.location?
=
?
new
?Point2D(x,?y);
??????}
??????
public
?Point2D?getLocation(?)?
{
????????
return
?location;
??????}
????}
????
public
?
class
?Position3D?
extends
?Position2D?
{
??????Point3D?location;
?

??????
public
?Position3D(
int
?x,?
int
?y,?
int
?z)?
{
????????
this
.location?
=
?
new
?Point3D(x,?y,?z);
??????}
??????
public
?Point3D?getLocation(?)?
{
????????
return
?location;
??????}
????????????

??????
public
?
static
?
void
?main(String[]?args)?
{
??????????Position2D?position?
=
?
new
?Position3D(
12
,?
23
,?
36
);
??????????Point3D?clone?
=
?(Point3D)position.getLocation();
??????????System.out.println(clone);
??????}
????}
為驗(yàn)證功能是否正確,我們看看運(yùn)行結(jié)果:
the position is x = 12,y = 23,z= 36