Super keyword to provide a value to a parent class

Katılım
10 Ocak 2023
Mesajlar
11
Puanları
1
Yaş
25
In Java, can I use the super keyword to provide a value to a parent class attribute from a child class

I'm a newbie who is attempting to utilize the ' super ' keyword in a setter method to apply a value to the parent class attribute 'price'. The parent class attribute does not appear to be changed outside of the class where I called the setter, but it appears to be updated within the class, and the "inherited?" version of price is updated despite the fact that I did not use the 'this' keyword.
Kod:
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;
    }

}
my output was: apple 100.0 fruit? 100.0 fruits 0.0

I thought it should be: apple 0.0 fruit? 100.0 fruits

What I'm missing?
 

Forum istatistikleri

Konular
128,191
Mesajlar
915,734
Kullanıcılar
449,967
Son üye
Gokhanttu

Yeni konular

Geri
Üst