【问题标题】:Class returning the extended class' parameter instead of it's own parameter when using an extended method [duplicate]使用扩展方法时返回扩展类的参数而不是它自己的参数的类[重复]
【发布时间】:2021-11-24 12:09:36
【问题描述】:

对不起,如果标题有点混乱!我得到了这个名为 Flower 的类,它扩展了一个 Plant 类(用于学校作业),我在 Plant 中有一个 getType() 方法,它只返回 this.type 。我的问题是,当我在 Flower 对象上运行此方法时,它没有返回 Flower 的类型,而是返回 null(这是 Plant 类中的默认返回)。我想知道是否有任何方法可以解决这个问题而不必重写该方法,因为这会破坏任务的全部意义。我的代码如下:

植物类:

public class Plant {
    
    protected List<String> plot = new ArrayList<>();
    private String type;
    
    public Plant() {
        //Some stuff here

        this.type = null;
    }
    
    public String getType() {
        return this.type;
    }
    //More stuff for the class here

花类:

public class Flower extends Plant {
    private String type;
    private int size;

    public Flower(String type) {
        this.plot = new ArrayList<>();
        this.type = type;
        this.size = 0;

        //More code not important for the question goes here...

提前感谢您的帮助!

【问题讨论】:

  • 为什么Flower 中有private String type;
  • 你在寻找shadowing

标签: java object oop inheritance extends


【解决方案1】:

您需要从 Flower 类中删除 private String type;

发生的情况是您的子类 (Flower) 声明了一个字符串“类型”,它隐藏了植物的“类型”字段。

这样想 - 孩子可以看到父母的字段,但父母看不到孩子的字段。

所以,当你在 Flower 中设置 type 时,它不适用于 Plant - 如果你没有在 Flower 中声明 type,当你在 Flower 中设置它时,@987654328 可以看到它@,因为那是它被声明的地方。

【讨论】:

  • 这还不够,因为typePlant 中是private。它还应该更改为protected,以便在Flower 的构造函数中设置。更好的是:Plant 的构造函数应该采用type 参数并将字段设置为该值,而不是默认为null。然后Flower 的构造函数必须调用super(type) 作为第一行,而不是设置this.type 本身。这允许typePlant 中保留private,甚至可以声明为final
【解决方案2】:

您面临的问题是,您的Plant 课程和您的Flower 课程都有自己的type。并且由于您在Flower 类中没有override getType() 方法,因此返回值将始终是Planttype,即null

您有一些选择可以解决这个问题。要么您执行与 plot 相同的操作,在其中创建字段 protected 并在 Flower 的构造函数中分配它。

public class Plant {
    protected List<String> plot;
    protected String type;

    public Plant() {
        this.plot = new ArrayList<>();
    }

    public String getType() {
        return this.type;
    }
}

public class Flower extends Plant {
    private int size;

    public Flower(String type) {
        this.type = type;
        this.size = 0;
    }
}

或者由于每个Plant 都有一个type,您可以使用“更干净”的版本,您可以使用superPlant 处理分配。

public class Plant {
    protected String type;
    protected List<String> plot;

    public Plant(String type) {
        this.type = type;
        this.plot = new ArrayList<>();
    }

    public String getType() {
        return this.type;
    }
}

public class Flower extends Plant {
    private int size;

    public Flower(String type) {
        super(type);
        this.size = 0;
    }
}

【讨论】:

    猜你喜欢
    • 2018-02-05
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 2011-05-12
    • 2017-07-27
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    相关资源
    最近更新 更多