【发布时间】: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