Java 檔案切割後
隸屬在同一個 package 資料夾
檔案:Car.java
package test1;
class Car {
   public void show() {
     System.out.println("Class Car");
   }
}  
檔案:CarTest1.java
package test1;
class CarTest {
   public static void main(String args[]){
     Car car = new Car();
     car.show();
   }
} 
編譯程式。我們讓系統自動產生儲存這些 class 檔案所在的資料夾 test1
$ javac -d ./ Car.java CarTest1.java檢視編譯結果:
$ ls -l test1 total 16 -rw-r--r-- 1 elvismeng staff 390 4 3 12:58 Car.class -rw-r--r-- 1 elvismeng staff 323 4 3 12:58 CarTest.class執行程式
$ java test1.CarTest Class Car
隸屬在不同的 package 資料夾
檔案:Car.java
package test2_1;
class Car {
   public void show() {
     System.out.println("Class Car");
   }
}  
檔案:CarTest1.java
package test2_2;
class CarTest {
   public static void main(String args[]){
     Car car = new Car();
     car.show();
   }
} 
編譯時,發生錯誤。為什麼?
ElvisdeMacBook-Pro:PackageManual elvismeng$ javac -d ./ Car.java CarTest1.java
CarTest1.java:5: error: cannot find symbol
     Car car = new Car();
     ^
  symbol:   class Car
  location: class CarTest
CarTest1.java:5: error: cannot find symbol
     Car car = new Car();
                   ^
  symbol:   class Car
  location: class CarTest
2 errors
這是因為兩個類別位於不同的 package,而無法存取對方,程式需改成
檔案:Car.java
package test2_1;
class Car {
   public void show() {
     System.out.println("Class Car");
   }
}
檔案:CarTest1.java
package test2_2;
class CarTest {
   public static void main(String args[]){
     test2_1.Car car = new test2_1.Car();
     car.show();
   }
}
編譯時,為何又有錯誤產生?
ElvisdeMacBook-Pro:PackageManual elvismeng$ javac -d ./ CarTest1.java
CarTest1.java:5: error: Car is not public in test2_1; cannot be accessed from outside package
     test2_1.Car car = new test2_1.Car();
            ^
CarTest1.java:5: error: Car is not public in test2_1; cannot be accessed from outside package
     test2_1.Car car = new test2_1.Car();
                                  ^
2 errors
錯誤原因在 Car 的存取權限要設為 public,所以程式需做下列修改
檔案:Car.java
package test2_1;
public class Car {
   public void show() {
     System.out.println("Class Car");
   }
}
檔案:CarTest1.java
package test2_2;
class CarTest {
   public static void main(String args[]){
     test2_1.Car car = new test2_1.Car();
     car.show();
   }
}
重新編譯
$ javac -d ./ Car.java javac -d ./ CarTest1.java編譯後會產生下列 package 資料夾與其相關類別檔案
$ ls -l test2_1 total 8 -rw-r--r-- 1 elvismeng staff 392 4 3 13:46 Car.class $ ls -l test2_2 total 8 -rw-r--r-- 1 elvismeng staff 327 4 3 13:46 CarTest.class執行結果
$ java test2_2.CarTest Class Car
沒有留言:
張貼留言