Today I wrote an exam and there was this question, which lines of code won't work if we write import countries.*; instead of package countries; in the TestCountry class. Here's the two classes:
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;
}
}
And
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();
}
}
Of course I tried it out and found out that the following lines wouldn't work anymore (if we outcomment package countries; and write import countries.*; instead):
System.out.println(isEuropean);
System.out.println(getNeighbors());
System.out.println(getName());
Can someone explain me why they don't work and what import countries.*; exactly does?
isEuropean,getName()are having default scope also called package scope. Your test was no longer in the same package as the class therefore it can only accesspublicandprotectedmembers (protected because it is subclass ofCountry. See this: docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html