[英]changes if using import instead of same package
今天我寫了一個考試,這里有一個問題,如果我們寫import countries.*;
話,哪幾行代碼行不通import countries.*;
而不是package countries;
在TestCountry
類中。 這是兩個類:
package countries;
public class Country {
private String name;
private int population;
boolean isEuropean;
public double area;
protected Country[] neighbors;
protected boolean inEurope() {
return this.isEuropean;
}
private void updatePopulation(int newBorns) {
this.population += newBorns;
}
public String toString() {
String str ="";
for (int i=0; i<this.neighbors.length; i++){
str += neighbors[i].name+"\n";
}
return str;
}
Countries[] getNeighbors() {
return this.neighbors;
}
String getName() {
return this.name;
}
}
和
import countries.*;
// package countries;
public class TestCountry extends Country {
public void run() {
System.out.println(name);
System.out.println(population);
System.out.println(isEuropean);
System.out.println(inEurope());
System.out.println(area);
System.out.println(toString());
updatePopulation(100);
System.out.println(getNeighbors());
System.out.println(getName());
}
public static void main(String[] args){
TestCountry o1 = new TestCountry();
o1.run();
}
}
當然,我嘗試了一下,發現以下幾行不再有用(如果我們不贊成package countries;
import countries.*;
而是寫import countries.*;
而是):
System.out.println(isEuropean);
System.out.println(getNeighbors());
System.out.println(getName());
有人可以向我解釋為什么他們不起作用以及什么import countries.*;
到底是什么?
由於尚未設置String getName()
和getNeighbors()
方法的范圍(可以在其中訪問),因此它們具有default package scope
即可以在同一包中使用。與isEuropean
.so變量isEuropean
您不能在其他軟件包中使用它們。 但是,由於您的test class
是擴展的Countries
類,因此可以訪問所有Countries
類的protected
成員
訪問級別
+---------------+-------+---------+----------+-------+
| modifiers | class | package | subclass | world |
+---------------+-------+---------+----------+-------+
| Public | Y | Y | Y | Y |
+---------------+-------+---------+----------+-------+
| Protected | Y | Y | Y | N |
+-----------------------+---------+----------+-------+
| Private | Y | N | N | N |
+---------------+-------+---------+----------+-------+
| No Modifiers | Y | Y | N | N |
+---------------+-------+---------+----------+-------+
System.out.println(getNeighbors());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.