簡體   English   中英

不能在子類的方法中使用超類的變量

[英]Can't use a variable from a superclass in method in subclass

我在使用超類的變量時遇到問題。 請參見下面的代碼。 在ConncetionMap(最終int n)中,我可以成功使用超類中的變量n,但是在重寫的Test()方法中,突然不再識別該變量n。 如何在那里繼續使用變量n?

我認為,如果ConncetionMap是公共的,則應該可以從同一類的其他位置訪問n。

public abstract class Connection {
    public Connection(final int n) {
    }

    public abstract int Test();
}


public class ConnectionMap extends Connection {

    public ConnectionMap (final int n) {
        super(n);

        //Here, n is recognized from the superclass and it simply works
        if (n < 0) {  
            throw new IllegalArgumentException("Error.");
        }
    }

    @Override
    public int Test() {
        int c = n; //This is an example usage of n, and here n is not recognized anymore.
    }
}

n是構造函數的參數。 參數(如局部變量)的作用域范圍是方法/構造函數。 因此,它僅在構造函數中可見。 這與超類BTW沒有太大關系。 只是具有可變范圍。

如果超類沒有提供任何獲取其值的方法(例如,使用受保護的或公共的getN()方法),則需要將其存儲到子類的字段中,以便能夠從另一個方法訪問它:

public class ConnectionMap extends Connection {

    private int n;

    public ConnectionMap (final int n) {
        super(n);

        //Here, n is recognized from the superclass and it simply works
        if (n < 0) {  
            throw new IllegalArgumentException("Error.");
        }
        this.n = n;
    }

    @Override
    public int test() {
        int c = this.n;
        ...
    }
}

您已在構造函數中將n聲明為局部變量(參數),因此在其范圍之外不可用。 嘗試這個:

public abstract class Connection {
    public final int n;
    public Connection(final int n) {
        this.n = n;
    }

    public abstract int Test();
}


public class ConnectionMap extends Connection {

    public ConnectionMap (final int n) {
        super(n);

        //Here, n is recognized from the superclass and it simply works
        if (n < 0) {  
            throw new IllegalArgumentException("Error.");
        }
    }

    @Override
    public int Test() {
        int c = n; //This is an example usage of n, and here n is not recognized anymore.
    }
}

在這里, n在構造函數傳遞給n在你的對象。 由於public > = protectedn從Connection繼承到ConnectionMap,因此可以在Test()使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM