今天我写了一个考试,有一个问题,如果我们在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.*;
):
System.out.println(isEuropean);
System.out.println(getNeighbors());
System.out.println(getName());
有人可以解释一下他们为什么不工作以及import countries.*;
到底做了什么?
答案 0 :(得分:1)
由于您尚未设置String getName()
,getNeighbors()
方法(可以访问它)的范围,因此它们具有default package scope
,即它们可以在同一个包中使用。与变量isEuropean
相同。所以你不能在另一个包中使用它们。
但是,由于protected
正在扩展Countries
类
test class
课程的所有Countries
成员都可以访问
访问级别
+---------------+-------+---------+----------+-------+
| 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 |
+---------------+-------+---------+----------+-------+
答案 1 :(得分:1)
System.out.println(getNeighbors());