【问题标题】:No error like class not defined没有类未定义的错误
【发布时间】:2016-08-21 17:13:14
【问题描述】:

我有以下二叉树的起始代码。我只是想知道,如果 BinaryTree 类尚未在 A 行和 B 行定义。为什么我在 A 行和 B 行报告时没有得到编译错误 - BinaryTree not defined。 我假设,C 行是完全定义类的地方。

public class BinaryTree {
private int data;
private BinaryTree left;  // Line A
private BinaryTree right;  // Line B

public BinaryTree(int num) {
this.data = num;
this.left = null;
this.right = null;
}
// getters and setters.
}  // Line C

【问题讨论】:

  • 在Java中没关系,我们需要头文件的不是C++。
  • 这是类的完整代码吗?
  • 这段代码编译得很好。 (就其本身而言,只为程序添加了一个main() 方法。)您是否有一个示例来说明您所描述的问题?

标签: java compilation


【解决方案1】:

为了扩展 tkausl 的评论,这里是关于范围界定的 Java 语言规范: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.3

具体来说:

顶级类型的范围(第 7.6 节)是声明顶级类型的包中的所有类型声明。

如果您跳到第 7.6 节,甚至还有一个示例可以解决您的问题:http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.6

示例 7.6-2。顶级类型的范围

package points;
class Point {
    int x, y;           // coordinates
    PointColor color;   // color of this point
    Point next;         // next point with this color
    static int nPoints;
}
class PointColor {
    Point first;        // first point with this color
    PointColor(int color) { this.color = color; }
    private int color;  // color components
}

这个程序定义了两个类,它们在类成员的声明中相互使用。因为 Point 和 PointColor 类类型具有包点中的所有类型声明,包括当前编译单元中的所有类型声明,作为它们的作用域,所以该程序可以正确编译。也就是说,前向引用不是问题。

为了完整起见,向前参考(我也必须查一下......): Forward reference vs. forward declaration

TLDR:Java 规范说这应该没问题,所以它是。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-22
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    相关资源
    最近更新 更多