我試圖更改locationNumber屬性的訪問修飾符,但它沒有幫助:
當我在 Market 物件上呼叫 getLocationNumber() 時,它回傳 0,而不是 34。我該怎么做才能解決這個問題?
public abstract class Location {
Collection<Figure> visitors;
protected int locationNumber;
public int getLocationNumber() {
return locationNumber;
}
}
public class Market extends Location {
protected int locationNumber = 34;
protected int[] sellingPrices;
uj5u.com熱心網友回復:
您的問題是您在子類中的定義在該子類中創建了另一個欄位。而這個欄位會影響超類欄位。
所以這里有兩種解決方案:
- 只是不要通過在子類中創建另一個具有相同名稱的欄位來隱藏超類欄位
- 使用
super關鍵字
例如像這樣:
class A {
protected int someInt = 0;
protected int letsShadow = 1;
void printInts() {
System.out.println(someInt);
System.out.println(letsShadow);
}
}
class B extends A {
protected int letsShadow = -1;
B() {
someInt = 42;
super.letsShadow = 43;
}
}
public class Main {
public static void main(String[] args) {
new B().printInts();
// exercise for the reader, what would print(new B().letsShadow) print?!
}
}
注意:現實世界的建議是首先避免使用受保護的欄位。只能在一個類中直接訪問您的欄位,任何其他類都應該使用方法。
uj5u.com熱心網友回復:
問題是您正在獲取超類中的欄位,而您正在填充子類中具有相同名稱的另一個欄位。您應該直接在超類上填充該欄位。您的 Market 類應該是這樣才能作業:
public class Market extends Location {
protected int[] sellingPrices;
public Market() {
super.locationNumber = 34;
}
}
這樣,當您創建Market實體時,您在超類中使用 34 填充 locationNumber。
相反,如果您在超類中不需要 locationNumber,您可以這樣做:
public class Market extends Location {
protected int[] sellingPrices;
protected int locationNumber = 34;
@Override
public int getLocationNumber() {
return locationNumber;
}
}
public abstract class Location {
Collection<Figure> visitors;
public abstract int getLocationNumber();
}
如果你不需要所有的實作Location都有getter,只需洗掉方法的抽象宣告
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/414235.html
標籤:
