返回类型错误 - 返回类型不兼容

时间:2021-01-10 18:09:47

标签: java visual-studio-code error-handling syntax

这是我的代码。我写了这个方法返回形状的主导点。最小,最大 2 点(左下,右上)。但是我的返回值出错,请在此处查看我的方法:

@Override
public Point2D[] getPoints() {
    Point2D[] ans = new Point2D[2];
    if (this._point1.getX()<=this._point2.getX()) {
        ans[0] =new Point2D(this._point1);
        ans[1] =new Point2D(this._point2);
    }
    else{
        ans[0] =new Point2D(this._point2);
        ans[1] =new Point2D(this._point1);
    }
    return ans;
}

这里是 Point2D 类:

public class Point2D implements GeoShape{
public static final double EPS1 = 0.001, EPS2 = Math.pow(EPS1,2), EPS=EPS2;
public static final Point2D ORIGIN = new Point2D(0,0);
private double _x,_y;
public Point2D(double x,double y) {
    _x=x; _y=y;
}
public Point2D(Point2D p) {
   this(p.x(), p.y());
}
public Point2D(String s) {
    try {
        String[] a = s.split(",");
        _x = Double.parseDouble(a[0]);
        _y = Double.parseDouble(a[1]);
    }
    catch(IllegalArgumentException e) {
        System.err.println("ERR: got wrong format string for Point2D init, got:"+s+"  should be of format: x,y");
        throw(e);
    }
}
public double x() {return _x;}
public double y() {return _y;}
public double getX() {return _x;}
public double getY() {return _y;}

public int ix() {return (int)_x;}
public int iy() {return (int)_y;}

public Point2D add(Point2D p) {
    Point2D a = new Point2D(p.x()+x(),p.y()+y());
    return a;
}
@Override
public String toString()
{
    return _x+","+_y;
}

public double distance()
{
    return this.distance(ORIGIN);
}
public double distance(Point2D p2)
{
    double dx = this.x() - p2.x();
    double dy = this.y() - p2.y();
    double t = (dx*dx+dy*dy);
    return Math.sqrt(t);
}

我在返回此方法 getpoints 时出错。检查这张图片:

here is the error message

返回类型与 GeoShape.getPoints() 不兼容。

有人知道这是什么原因吗?

1 个答案:

答案 0 :(得分:0)

<块引用>
@Override
public Point2D[] getPoints() {

返回类型与 GeoShape.getPoints() 不兼容

无论这是在哪个类中,它implements GeoShape。并且 GeoShapes 必须具有 Rectange getPoints() 方法。或者不管它是什么 - 一个返回特定内容的 getPoints 方法,并且该特定内容不是 Point2D[] 的超类型 - 您没有粘贴它。

  1. 所有的苹果都是水果。所有(无论 Point2D[] getPoints() 方法是什么)都是一个 GeoShape。
  2. GeoShapes 有一个返回矩形的 getPoints() 方法。
  3. 我可以将您的(无论是什么)视为 GeoShape。
  4. 因此您的(无论是什么)必须有一个 Rectangle getPoints() 方法。
  5. 但它不会,因此,编译器错误。

修复方法是 [A] 停止实现 GeoShape,[B] 更改 GeoShape 的 getPoints 方法以返回 Point2D[],或者 [C] 更改您的返回类型getPoints 方法来匹配 GeoShape 中 getPoints 方法的返回类型。