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

Java继承编译失败:Repair类未正确调用父类带参构造器

问题:继承Loot类的Repair编译报错,运行时构造器参数不匹配

使用Apache NetBeans IDE开发游戏,编写Repair类继承Loot类后,IDE提示文件无法编译但未明确指出错误位置。运行程序时抛出异常,提示entity.Loot类的构造器需要main.GamePanel、double、double类型参数,但Repair的构造器未调用该带参构造器。

Repair类代码

package entity;

import java.awt.Graphics2D;
import main.Game;
import main.GamePanel;


public class Repair extends Loot{
       
    public Repair(GamePanel gp, double x, double y) {
        this.gp = gp;
        width = 20;
        height = 20;
        this.x = x - width/2;
        this.y = y - height/2;
        trackX = 0;
        trackY = 0;
    }
    
    @Override
    public void update() {
        
    }
    @Override
    public void draw(Graphics2D g2) {
        g2.drawImage(image, Game.round(x), Game.round(y), null);
        // DEBUG
        // this.drawHitboxes(g2);
    }
}

错误栈信息

Exception in thread "Thread-0" java.lang.RuntimeException: Uncompilable code - constructor Loot in class entity.Loot cannot be applied to given types;
  required: main.GamePanel,double,double
  found:    no arguments
  reason: actual and formal argument lists differ in length
    at entity.Repair.<init>(Repair.java:1)
    at entity.Enemy.spawnLoot(Enemy.java:144)
    at entity.Enemy.update(Enemy.java:156)

解决方案

  • 问题核心:Java子类构造器默认会调用父类的无参构造器,但Loot类仅提供了带GamePanel, double, double三个参数的构造器,因此必须在子类构造器中显式调用父类的带参构造器。
  • 修改Repair构造器,在代码第一行添加super(gp, x, y);,确保父类构造器能获取到所需参数:
public Repair(GamePanel gp, double x, double y) {
    super(gp, x, y); // 显式调用父类带参构造器
    width = 20;
    height = 20;
    this.x = x - width/2;
    this.y = y - height/2;
    trackX = 0;
    trackY = 0;
}
  • 注意:如果Loot类的构造器已经对x、y坐标做过偏移处理,需检查子类的this.x、this.y赋值是否重复,避免坐标错误。

内容的提问来源于stack exchange,提问作者William Li

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 12:50:05