【问题标题】:changes if using import instead of same package如果使用导入而不是相同的包,则会发生变化
【发布时间】:2017-12-19 16:50:56
【问题描述】:

今天我写了一个考试,有一个问题,如果我们在TestCountry类中写import countries.*;而不是package countries;,哪些代码行将不起作用。这是两个类:

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.*; 到底是做什么的?

【问题讨论】:

  • 如果没有修饰符,isEuropeangetName() 具有默认范围,也称为 package 范围。您的测试不再与该类在同一个包中,因此它只能访问publicprotected 成员(受保护,因为它是Country 的子类。请参阅:docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

标签: java import package


【解决方案1】:

由于您没有设置String getName()getNeighbors() 方法的范围(可以访问),所以它们具有default package scope,即它们可以在同一个包中使用。变量@ 也是如此987654324@.so 你不能在另一个包中使用它们。 但是你的Countries 类的所有protected 成员都可以访问,因为你的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   |
+---------------+-------+---------+----------+-------+

【讨论】:

    【解决方案2】:
    System.out.println(getNeighbors());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 2021-06-27
      • 2020-06-19
      • 1970-01-01
      相关资源
      最近更新 更多