繁体   English   中英

如果使用导入而不是相同的软件包,则更改

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM