何时使用嵌套类?

下面的代码将找到2行的交集并返回点对象。 如果只有IntersectionOf2Lines类创建point,我应该指出一个嵌套类吗? 如果不是那么为什么不呢? 谢谢

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

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

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

 package main; public class Main { public static void main(String[] args) { MyPoint p = new MyPoint(); px = 5; System.out.println("x: "+ px); } private static class MyPoint { int x; } } 

数学上,Line由多个点组成。 如果要在外部创建Point类,可以使用它来显示特定行,行的结束点上的点,因此它应该是普通类而不是IntersectionOf2Lines的嵌套类。

如果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 ),并且您不希望其他人实例化“您的”类,则这尤其有用,因为这会创建一个额外的依赖项。