3

下面的代码将找到 2 条线的交点并返回点对象。如果点只能由 IntersectionOf2Lines 类创建,我应该将点设为嵌套类吗?如果不是那么为什么不呢?谢谢

class Point {
    private final int x;
    private final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    int getX() {
        return x;
    }

    int getY() {
        return y;
    }
}

public class IntersectionOf2Lines {

    public static Point calculateIntersection(Line line1, Line line2) {
        int x = (line2.getConstant() - line1.getConstant()) / (line1.getSlope() - line2.getSlope());
        int y = line1.getSlope() * x + line1.getConstant();

        return new Point(x, y);
    }
4

3 回答 3

1

如果任何其他类都不需要 Point 类,并且 Point 类不需要访问 IntersectionOf2Lines 的私有类成员,那么您可以将 Point 类设为静态嵌套类

静态嵌套类是一个较轻的内部类,它无法访问超类成员,并且经常像 C 中的结构一样使用。

package main;

public class Main {

    public static void main(String[] args) {

        MyPoint p = new MyPoint();
        p.x = 5;
        System.out.println("x: "+ p.x);

    }

    private static class MyPoint {
        int x;
    }

}
于 2013-06-15T23:05:52.800 回答
0

如果Point仅由创建IntersectionOf2Lines,我会将其实现为静态嵌套类:这样您可以将构造函数声明为private

public class IntersectionOf2Lines {
    static class Point {
        private final int x;
        private final int y;

        private Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        int getX() {
            return x;
        }

        int getY() {
            return y;
        }
    }

    public static Point calculateIntersection(int line1, int line2) {
        int x = 1;
        int y = 2;

        return new Point(x, y);
    }

如果构造函数是private,编译器会强制执行您的设计/意图。

这特别有用,如果包含结果的类的可见性是public(在您的示例中,它是package private),并且您不希望其他人实例化“您的”类,因为这会产生额外的依赖关系。

于 2013-06-16T17:57:39.333 回答
0

在数学上,线由点数组成。如果你在外面创建点类,你可以用它来显示特定线上的点,线的端点,所以它应该是一个普通的类而不是 IntersectionOf2Lines 的嵌套类。

于 2013-06-16T18:05:56.750 回答