簡體   English   中英

我可以使用 Java 中子 class 的 super 關鍵字為父 class 屬性賦值嗎?

[英]Can I assign a value to a parent class attribute using super keyword from the child class in Java?

這里的新手試圖在 setter 方法中使用“super”關鍵字來為父 class 屬性“price”賦值。 父 class 屬性在我調用 setter 的 class 之外沒有得到更新,盡管它似乎在 class 和“繼承?”中得到更新。 即使我沒有使用“this”關鍵字,價格版本也會更新。 我錯過了什么? 謝謝。 `

package Practice.FruitConst;

public class App {
    public static void main(String[] args) {

        Fruit fruit = new Fruit();
        Apple apple = new Apple();
    apple.setPrice(100.0);
       apple.pp();
        System.out.println("fruit " + fruit.price);

    }
}

class Apple extends Fruit{
    @Override
    public void setPrice(Double price) {
        super.price = price;
    }

    public void pp(){
        System.out.println("apple " + this.price);

        System.out.println("fruit? " + super.price);
    }
}

class Fruit {

    String name;
    String color;
    double price;

    @Override
    public String toString() {
        return "\n" + getClass().getSimpleName() +
                "name='" + name + '\'' +
                ", color='" + color + '\'' +
                ", price='" + price + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

}

我的 output 是:蘋果 100.0 水果? 100.0 水果 0.0

我想應該是:apple 0.0 fruit? 100.0 水果 100.0

你誤解了price變量的scope。 這是一個實例變量,這意味着該類型的每個實例都有自己的price 它在Fruit class 上定義,但它可用於Apple等子類。

您已經創建了兩個單獨的 object 實例 - 一個Apple和一個Fruit 它們在兩個實例之間不共享任何值。 因此,為其中一個設定價格對另一個沒有影響。

暫無
暫無

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

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