gpt4 book ai didi

java - java中的构造函数和抽象类

转载 作者:行者123 更新时间:2023-11-30 07:09:17 25 4
gpt4 key购买 nike

我有一个抽象类 Entity.java 和一个扩展它的类 Magician.java。每当我创建一个 new Magician("Ged", 300);然后调用 System.out.println() 它总是打印 null(0),我不确定为什么它应该打印 Ged(300)。相关代码如下:

实体字段/构造函数:

public abstract class Entity {

protected String name;
protected int lifePoints = 0;

public Entity(String name, int lifePoints) {
assert (lifePoints >= 0);
this.name = name;
this.lifePoints = lifePoints;
}

...

}

魔术师 字段/构造函数/toString:

public class Magician extends Entity implements SpellCaster {

public Magician(String name, int lifePoints) {
super(name, lifePoints);
// TODO Auto-generated constructor stub
}

protected String name;
protected int lifePoints;

...

public String toString() {
return name + "(" + lifePoints + ")";
}

}

主要类:

public static void main(String[]args) {

Magician m1=new Magician("Ged",300);
System.out.println(m1.toString());
}

提前致谢。

最佳答案

您正在隐藏子类 Magician 中父类(super class) Entity 的实例字段 namelifePoints .

默认情况下分别设置为 null 和 0。从子类 Magician 中删除那些实例字段声明。

public class Magician extends Entity implements SpellCaster {

public Magician(String name, int lifePoints) {
super(name, lifePoints);
// TODO Auto-generated constructor stub
}


...

public String toString(){
return name + "(" + lifePoints + ")";
}

}

关于java - java中的构造函数和抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23291434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com