1
package p1;
public class Protection {
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
包P2包P1不存在包含三個文件demo.java,OtherPackage.java和Protection2.java:錯誤:從包編譯Java文件P2
//Demo package p2.
package p2;
//Instantiate various classes in p2.
public class Demo {
public static void main(String[] args) {
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
package p2;
OtherPackage.java
class OtherPackage {
OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("Other package constructor");
//class or package only
//System.out.println("n = " + p.n);
//class only
//System.out.println("n_pri = " + p.n_pri);
//class, subclass or package only
//System.out.println("n_pro = " + p.n_pro)
System.out.println("n_pub = " + p.n_pub);
}
}
和Protection2.java
package p2;
class Protection2 extends p1.Protection {
Protection2() {
System.out.println("Derived other package constructor");
//class or package only
//System.out.println("n = " + n);
//class only
//System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
我試圖從包P2編譯Demo.java:
:~/Desktop/Examples/p2$ javac *.java
I產生以下錯誤
Protection2.java:3: error: package p1 does not exist
class Protection2 extends p1.Protection {
^
OtherPackage.java:5: error: package p1 does not exist
p1.Protection p = new p1.Protection();
^
OtherPackage.java:5: error: package p1 does not exist
p1.Protection p = new p1.Protection();
^
Protection2.java:13: error: cannot find symbol
System.out.println("n_pro = " + n_pro);
^
symbol: variable n_pro
location: class Protection2
Protection2.java:14: error: cannot find symbol
System.out.println("n_pub = " + n_pub);
^
symbol: variable n_pub
location: class Protection2
5 errors
我試圖導入包P1,但它與上述5個錯誤沿着增加了另一個錯誤:
Demo.java:4: error: package p1 does not exist
import p1.Protection;
試試'CD〜/桌面/ Examples'和編譯'P2/* java' – ajb
,因爲你還沒有告訴它在哪裏尋找它找不到'p1',所以只默認在當前目錄中查找,並且當前目錄中不存在「p1」。做@ajb所說的,即從父目錄運行編譯器,所以'p1'和'p2'都存在於當前目錄中。另外,如果你堅持從'p2'運行編譯器,就這樣做:'javac -cp .. * .java' – Andreas