如何为自定义形状编写包含方法 class

How to write a contains method for custom Shape class

我正在尝试为自定义形状 class 编写包含方法,但如果可能的话,我更愿意简单地编写自己的方法而不实现形状 class。

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

[编辑]

这是一个例子class

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);
  }

另一个

public class Rect extends BoundedShape {
  public Rect(Color color, Point corner, int wide, int high) {
    super(color, corner, wide, high);
  }
  public void draw(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(strokeColor);
    g2d.drawRect(upperLeft.x, upperLeft.y, width, height);
  }
}

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

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。现在您可以为其他 classes 编写类似的方法,例如矩形你可以勾选 this.