簡體   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