Java子类用super给父类属性赋值为何父类实例属性未更新?
问题分析:子类继承属性与独立父类实例的关系
核心误解
你搞混了子类实例中继承的父类属性和单独创建的父类实例属性——这是两个完全独立的内存对象,彼此没有任何关联。
具体解释
实例的独立性
new Fruit()和new Apple()创建的是两个毫无关系的对象:前者是纯粹的Fruit实例,后者是Apple实例(它内部包含父类Fruit的属性结构,但和前者不是同一个东西)。- 你在Apple的
setPrice里用super.price = price,修改的只是当前Apple实例内部继承自Fruit的price属性,和你单独new的那个Fruit实例完全无关,所以那个独立Fruit的price还是默认值0.0。
this.price和super.price的本质- 你的Apple类没有自己定义
price属性,所以this.price会自动向上查找父类的price属性,和super.price访问的是同一个变量——也就是当前Apple实例里父类部分的price。这就是为什么两者输出都是100.0的原因。 - 如果你想让Apple拥有自己独立的price,需要在Apple类里显式定义
double price;,此时this.price访问子类自己的属性,super.price访问父类继承来的属性,但这仍然和独立的Fruit实例没关系。
- 你的Apple类没有自己定义
如何达到你的预期输出
- 你的预期里想让独立Fruit实例的price变成100.0,只能直接调用该实例的
setPrice方法:fruit.setPrice(100.0);。 - 如果同时想让Apple自己的price是0.0,需要在Apple类里定义自己的price属性,并在
setPrice里单独设置子类的price。
- 你的预期里想让独立Fruit实例的price变成100.0,只能直接调用该实例的
修正示例代码
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(); // 直接修改独立Fruit实例的属性 fruit.setPrice(100.0); System.out.println("fruit " + fruit.price); } } class Apple extends Fruit{ // 子类定义自己的price属性 double price; @Override public void setPrice(Double price) { super.price = price; // 修改父类继承的price this.price = 0.0; // 修改子类自己的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; } }
修正后输出
apple 0.0 fruit? 100.0 fruit 100.0
内容的提问来源于stack exchange,提问作者arthur
相关产品推荐
相关产品推荐

