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

Java继承实践:对象字符串传递时保护者名称显示null问题

Bug根因
  • 属性归属错误:protector字段错误定义在SuperPerson类中,属于Hero/Villian实例自身的属性,但「保护者身份」本质是被保护的目标对象的属性,存到发起保护的Hero实例中,其他对象无法读取到正确值。
  • 赋值逻辑错误:代码中this.protector = this.name是将保护者名称存到当前发起保护的Hero实例的protector字段中,只有h1实例的protector是Spiderman,h2、v1实例的protector始终是默认值null,输出时自然显示null。
  • 字符串比较不规范:用!=比较字符串内容,应该使用equals()方法。
修复步骤

1. 调整属性归属

将protector字段从SuperPerson移到Person类中,同时补全Person类缺失的公共属性:

public class Person {
    boolean protection;
    String protector; // 保护者属性归属于被保护的目标对象
    String name;
    int health;
    String type;
    // 请补全对应构造方法
}

同时删除SuperPerson类中冗余的protector字段:

public class SuperPerson extends Person {
    // 移除原有protector定义
    // 保留你原有的其他属性和方法即可
}

2. 修正Hero类protect方法逻辑

所有protector的读写都针对目标对象target操作,而不是当前Hero实例本身:

public class Hero extends SuperPerson {
    void protect(Person target) {
        if(target.type.equals("Super Villian")) {
            System.out.println("You can not protect a villian!");
        }
        else {
            if(target.health != 0) {
                if(!target.protection) {
                    target.protection = true;
                    target.protector = this.name; // 赋值给目标对象的protector
                    System.out.println(target.name + " is under " + target.protector + "'s protection.");
                }
                else {
                    if(!target.protector.equals(this.name)) { // 用equals比较字符串内容
                        System.out.println(target.name + " is already under " + target.protector + "'s protection");
                    }
                    else {
                        target.protection = false;
                        target.protector = null; // 取消保护时清空属性
                        System.out.println(target.name + " is no longer under " + this.name + "'s protection");
                    }
                }
            }
            else {
                System.out.println("Target is already dead.");
            }
        }
    }
}

3. 修正Villian类attack方法逻辑

读取目标对象的protector属性输出:

public class Villian extends SuperPerson{
    int attack(Person target) {
        if(target.type.equals(this.type)) {
            System.out.println("Invalid target!");
            return 0 ;
        }
        else {
            if(target.protection) {
                System.out.println("The target is under " + target.protector + "'s protection");
                return 0;
            }
            else {
                return super.attack(target);
            }
        }
        
    }
}
修复后输出结果
Mary is under Spiderman's protection.
Mary is already under Spiderman's protection
The target is under Spiderman's protection

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 10:24:04