Reputation: 117
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?
Upvotes: 1
Views: 38
Reputation: 1165
since you have not set the scope of the String getName()
, getNeighbors()
method(where it can be accessible), so they have default package scope
i.e they can be used within the same package.same is with the variable isEuropean
.so you can not use them in another package.
But all the protected
member of your Countries
class can be accessible since your test class
is extending Countries
class
Access Levels
+---------------+-------+---------+----------+-------+
| 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 |
+---------------+-------+---------+----------+-------+
Upvotes: 1