在Java1.4及以前,子類方法如果要覆蓋超類的某個方法,必須具有完全相同的方法簽名,包括返回值也必須完全一樣。
Java5.0放寬了這一限制,只要子類方法與超類方法具有相同的方法簽名,或者子類方法的返回值是超類方法的子類型,就可以覆蓋。
注意:"協變返回(covariant return)",僅在subclass的返回類型是superclass返回類型的extension時才被容許。
package com.eric.news;
public 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;
}
}
package com.eric.news;
public 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;
}
}
package com.eric.news;
public 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;
}
}
package com.eric.news;
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;
}
}
posted on 2008-04-22 22:45
周銳 閱讀(286)
評論(0) 編輯 收藏 所屬分類:
Java