如果使用import而不是相同的包,则更改

问题描述 投票:1回答:2

今天我写了一个考试,有一个问题,如果我们在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.*;究竟做什么?

java import package
2个回答
1
投票

因为你还没有设置String getName()getNeighbors()方法(它可以访问的地方)的范围,所以它们有default package scopei.e它们可以在同一个package.same中使用变量isEuropean.so你不能在它们中使用它们另一个包。但是你的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
投票
System.out.println(getNeighbors());
© www.soinside.com 2019 - 2024. All rights reserved.