2016-08-21 100 views
-1

我有以下二叉樹的開始代碼。我只是想知道,如果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 
+2

它在Java中並不重要,那不是C++,我們需要頭文件。 – tkausl

+0

這是全班級的完整代碼嗎? –

+0

這段代碼編譯得很好。 (就其本身而言,只需爲該程序添加一個'main()'方法)。您是否有示例說明您描述的問題? – David

回答

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規範說,這應該是好的,所以它是。