如何为自定义Shape类编写contains方法

时间:2015-05-09 02:46:09

标签: java equals contains shape

我正在尝试为自定义Shape类编写一个contains方法,但如果可能的话,我希望在不实现Shape类的情况下编写自己的方法。

但是,我该如何编写这样一种方法来测试是否指定X& Y坐标在我的形状内还是在边界上?

[编辑]

这是一个示例类

!=

另一个

abstract class BoundedShape extends Shape {
  protected Point upperLeft;
  protected int width, height;
  public BoundedShape(Color color, Point corner, int wide, int high) {
    strokeColor = color;
    upperLeft = corner;
    width = wide;
    height = high;
  }
  public void setShape(Point firstPt, Point currentPt) {
    if (firstPt.x <= currentPt.x)
      if (firstPt.y <= currentPt.y)
        upperLeft = firstPt;
      else
        upperLeft = new Point(firstPt.x, currentPt.y);
    else if (firstPt.y <= currentPt.y)
      upperLeft = new Point(currentPt.x, firstPt.y);
    else
      upperLeft = currentPt;

    width = Math.abs(currentPt.x - firstPt.x);
    height = Math.abs(currentPt.y - firstPt.y);
  }
}

另一个

public class Line extends Shape {
  protected Point firstPoint;
  protected Point secondPoint;

  public Line(Color color, Point p1, Point p2) {
    strokeColor = color;
    firstPoint = p1;
    secondPoint = p2;
  }
  public void setEndPoint(Point endPoint) {
    secondPoint = endPoint;
  }
  public void draw(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(strokeColor);
    g2d.drawLine(firstPoint.x, firstPoint.y, secondPoint.x,
        secondPoint.y);
  }

1 个答案:

答案 0 :(得分:1)

您必须在抽象类contains()中将Shape方法声明为:

abstract public class Shape {
    abstract boolean contains(Point point);
    double distance(Point a, Point b) {
        return Math.sqrt((a.getX()-b.getX())*(a.getX()-b.getX()) + (a.getY()-b.getY())*(a.getY()-b.getY()));
    }
}

方法distance()将用于计算两点之间的距离。现在,您需要在Line中实现contains()

public class Line extends Shape {
    private Point firstPoint;
    private Point secondPoint;

    public Line(Point firstPoint, Point secondPoint) {
        this.firstPoint = firstPoint;
        this.secondPoint = secondPoint;
    }

    @Override
    boolean contains(Point point) {
       return (distance(firstPoint, point) + distance(secondPoint, point) == distance(firstPoint, secondPoint));
    }

}

这可以测试为:

public static void main(String[] args) {
        Shape shape = new Line(new Point(10,10),new Point(10,40));
        boolean result = shape.contains(new Point(10,20));
        System.out.println(result);
    }

上述代码的输出为true。现在你可以为其他类编写类似的方法,例如矩形,你可以检查this