You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java继承构造函数参数异常:传入值为何最终变为0?

问题原因及解决办法

问题原因

你的代码里拷贝构造函数的赋值方向完全写反了,这是所有属性变为0的核心原因:

  • Box类的拷贝构造函数中,你写的是obj.length = length;,此时新创建的Box对象的length是Java默认的0值,这行代码会把传入的参数对象(比如box1)的length覆盖为0,而不是把参数对象的属性值赋值给新对象。
  • WeightBox类的拷贝构造函数同理,obj.weight = weight;会把传入的参数对象的weight覆盖为新对象的默认0值。

当你创建box3 = new WeightBox(box1)时,首先调用super(obj)触发Box的错误拷贝构造函数,把box1的length/width/height改成0,接着又把box1的weight改成0,最终导致box1、box3的所有属性全为0。

解决办法

修正两个拷贝构造函数的赋值方向,把参数对象的属性值赋值给当前新对象:

修正Box类的拷贝构造函数

Box(Box obj) {
    length = obj.length;
    width = obj.width;
    height = obj.height;
}

修正WeightBox类的拷贝构造函数

WeightBox(WeightBox obj) {
    super(obj);
    weight = obj.weight;
}

修正后运行代码,就能得到预期输出:

Box no. 1 length = 10.0 width = 20.0 height =30.0 volume = 6000.0 Weight = 40.0


Box no. 2 length = 10.0 width = 10.0 height =10.0 volume = 1000.0 Weight = 20.0


Box no. 3 length = 10.0 width = 20.0 height =30.0 volume = 6000.0 Weight = 40.0

内容的提问来源于stack exchange,提问作者C J

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:07:08