在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