packagetina;classHumanTest{publicstaticvoidmain(String[] args){Human h1 =newHuman(); }// end of main(String[])}//end of HumanTest
這個 HumanTest.java位於套件tina中,可以直接存取到Human這個類別。
但若位在不同套件,就存取不到。
packagerun;classTest{publicstaticvoidmain(String[] args){Human h1 =newHuman(); // compile error: Human cannot be resolved to a type }// end of main(String[])}// end of class Test
出現編譯錯誤的訊息:The public type Animal must be defined in its own file
也就是說,要用public修飾的外部類別,只能是『與檔名相同』的那個類別。
好,但是為什麼public只能修飾與檔名相同的外部類別呢?
很遺憾的告訴你,因為這是Java規定的。(兇手如下圖↓)
Gosling James (Java Founder)
在JLS (Java Language Specification,Java語言規範) 第7.6節提到,
Top Level Type Declarations: (這裡的 Top Level Type就是本章節說的最外層類別)
This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a Java compiler to find a named class within a package. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.
package tina;
public class Human{
// code...
}// end of class Human
package run;
import tina.Human;
class Test{
public static void main(String[] args){
Human h1 = new Human(); // 有import就可以直接使用
tina.Human h2 = new tina.Human(); // 利用完整類別路徑也行
}// end of main(String[])
}// end of class Test
// 保護
protected class Human{
// code...
}
// 私有
private class Human{
// code...
}
class Human{
// code..
}
class Animal{
// code...
}
public class Human{
// code...
}
class Animal{
// code...
}
class Human{
// code...
}
public class Animal{ //編譯錯誤
// code...
}