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

Getter/Setter方法使用是否正确?Driver类代码报错求助

问题分析与修复方案

一、Driver类代码里的明显错误

  1. 无效的setVehicle方法:你写了一个public Drivable setVehicle()方法,首先拼写错了Driveable(多写了一个i),其次这个方法既无参数也无有效返回值,完全不符合setter规范,属于冗余错误代码,直接删掉即可。
  2. 构造方法调用可优化:原构造方法调用this()后再调用setName、setEmail,如果父类User有带name和email的构造方法,直接用super(name, email)调用更合理。
  3. 字段初始化建议:原代码直接初始化vehicle = new Vehicle(),后续通过构造方法传入实例会覆盖这个值,不如留空让构造方法或setter赋值更灵活。

修复后的Driver类代码

public class Driver extends User { 
    
    private Driveable vehicle;
    
    public Driver() {}
    
    public Driver(Vehicle vehicle, String name, String email){
        super(name, email); // 若User类无对应构造方法,保留原setName/setEmail调用即可
        this.vehicle = vehicle;
    }
 
    public Driveable getVehicle(){
        return vehicle;
    }
    
    public void setVehicle(Vehicle vehicle){
        this.vehicle = vehicle;
    }
    
    public void drive(){
        // 增加空指针判断,避免vehicle为null时调用方法报错
        if(vehicle != null) {
            vehicle.drive();
        }
    }
}

二、报错信息对应的两个问题

1. 编译错误:Driver类缺少必要方法

报错里的class Driver does contain the required methods应为笔误,实际是does NOT contain,原因就是那个无效的setVehicle方法干扰了方法检测,删掉它之后,剩余的getVehicle和带参数的setVehicle就能满足要求。

2. 运行时错误:找不到TaxiService类

报错java.lang.NoClassDefFoundError: TaxiService说明:

  • 项目中缺少TaxiService类的代码文件,或者编译后的.class文件未在类路径中
  • 若该类是作业要求实现的,需补写对应的类代码
  • 若为依赖类,要确保它被正确添加到项目的类路径中

额外检查点

  • 确认Vehicle类已经实现了Driveable接口,且包含drive()方法,否则Driver的drive()方法会调用失败
  • 检查父类User的setName、setEmail方法是否存在,确保Driver能正常调用

内容的提问来源于stack exchange,提问作者Brian Countryman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:18:24