假设我有一个抽象类字符,它有字段health和maxHealth。maxHealth在子类之间有所不同。然而,我实现它的第一种方式-- health总是被初始化为等于maxHealth。
公共抽象类字符{受保护的向量位置;受保护的int健康;受保护的int maxHealth;公共字符(浮点xLocation,浮点yLocation){向量位置=新向量( xLocation,yLocation);yLocation= maxHealth;}公共类Grunt扩展字符{ public Grunt(float xLocation,float yLocation){ super(xLocation,yLocation);maxHealth = 200;}}
但是,由于health在maxHealth被初始化为200之前被分配给了maxHealth,所以这不能正常工作。
我试图按如下方式更改构造函数参数,但我不确定这是否是一个良好的实践。你认为如何?
public abstract class Character {
protected Vector position;
protected int health;
protected int maxHealth;
public Character(float xLocation, float yLocation, int maxHealth){
Vector position = new Vector(xLocation, yLocation);
this.maxHealth = maxHealth;
health = maxHealth;
}
}
public class Grunt extends Character {
public Grunt(float xLocation, float yLocation){
super(xLocation, yLocation, 200);
}
}发布于 2018-05-07 11:01:38
另一种方法是,以后能够更改值,使用setter。如果您可能实现任何奖金,MaxHealth可能会更改。
public void setMaxHealt(int maxHealth){
this.maxHealth = maxHealth;
this.health = maxHealth;
}在构造函数中,只需使用setter。
public Grunt(float xLocation, float yLocation){
super(xLocation, yLocation);
setMaxHealth(200);
}使用构造函数是很好的,并且是一个很好的解决方案,老实说,但是当您发现构造函数有20个参数时.你需要其他解决方案。
注意:
因为我说过,如果您不想“治愈”您的角色,如果您的健康状况不充分,可以在更改值(如果是this.health == this.maxHealth )之前检查一下,并根据此值设置值。
发布于 2018-05-02 10:46:50
与其质疑它是否是一个好的实践,它将更有帮助了解您的第一段代码的实际工作。关于对象的创建,JLS§15.9.4有这样一个说法:
新对象包含在指定的类类型中声明的所有字段及其所有超类的新实例。在创建每个新字段实例时,它将初始化为其默认值(§4.12.5)。
这意味着health和maxHealth在构造函数执行之前就被初始化为0。所以您的语句health = maxHealth;是完全没有意义的,因为health只被分配给已经分配给它的默认值。
我认为您的第二个版本没有问题(除了一个不存在的Vector构造函数的使用,我在评论中已经暗示了这一点)。每个字段都是在声明它的类的构造函数中初始化的,尽管这对于非final字段来说并不是绝对必要的,但仍然使代码更容易阅读,因为您不必跳过类来理解字段的初始化。
此外,类Vector 是过时的。如果不需要同步,那么使用ArrayList会更好(如果需要,还有更好的解决方案,如链接中所解释的那样)。此外,您使用的是原始类型,因此拒绝了泛型提供的附加类型安全性。
实际上,在您的两个版本中都存在一个我之前没有注意到的问题:您的构造函数从不为实例变量position分配值。相反,他们声明一个名为position的局部变量,该变量隐藏实例变量。要纠正这一点,您需要从赋值中删除类型声明Vector,以便:
Vector position = new Vector(xLocation, yLocation); //declares a local variable unrelated to `Character.position`变成这样:
position = new Vector(xLocation, yLocation); //refers to Character.positionhttps://codereview.stackexchange.com/questions/193432
复制相似问题