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

Java继承时调用父类getType返回null 不重写方法如何解决?

问题根源

你的代码触发了Java的*属性隐藏(Field Hiding)*机制:

  • 父类Plant已经定义了私有的type成员变量
  • 子类Flower又重复定义了一个同名的私有的type成员变量,二者是完全独立的两个属性,不存在重写关系
  • 父类的getType()方法属于Plant类,内部访问的this.type永远指向父类自身定义的type变量,默认值为null,和子类的type属性毫无关联,因此调用时会返回null

解决方案(均无需重写getType()方法)

方案1:保留父类封装性,新增protected设置方法(规范写法)

修改Plant类,新增供子类调用的setType方法:

public class Plant {
    protected List<String> plot = new ArrayList<>();
    private String type;
    
    public Plant() {
        //Some stuff here
        this.type = null;
    }
    
    // 新增protected修饰的设置方法,子类可直接调用
    protected void setType(String type) {
        this.type = type;
    }
    
    public String getType() {
        return this.type;
    }
    //More stuff for the class here
}

修改Flower类,删除重复的type定义,构造方法中调用父类的setType赋值:

public class Flower extends Plant {
    // 删掉重复定义的private String type
    private int size;

    public Flower(String type) {
        this.plot = new ArrayList<>();
        // 调用父类方法给父类的type属性赋值
        setType(type);
        this.size = 0;
        //More code not important for the question goes here...
    }
}

方案2:修改父类type的访问修饰符(作业场景更简便)

修改Plant类的type属性修饰符为protected,让子类可以直接访问:

public class Plant {
    protected List<String> plot = new ArrayList<>();
    // 将private改为protected,子类可直接读写
    protected String type;
    
    public Plant() {
        //Some stuff here
        this.type = null;
    }
    
    public String getType() {
        return this.type;
    }
    //More stuff for the class here
}

修改Flower类,删除重复的type定义,构造方法中直接给父类的type赋值:

public class Flower extends Plant {
    // 删掉重复定义的private String type
    private int size;

    public Flower(String type) {
        this.plot = new ArrayList<>();
        // 直接给父类的type属性赋值
        this.type = type;
        this.size = 0;
        //More code not important for the question goes here...
    }
}

两种方案修改完成后,调用Flower实例的getType()方法即可返回正确的type值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:54:02