gpt4 book ai didi

java - 使用 'this' 关键字调用基本构造函数并使用方法调用来设置私有(private)成员

转载 作者:行者123 更新时间:2023-12-02 03:39:00 24 4
gpt4 key购买 nike

几个问题:

1) 如果您有一个父类(super class) Monster 并且您创建了一个继承其行为的子类。在子类的每个构造函数中调用super是一种很好的做法。下面我所做的是在第一个重载构造函数中调用它一次,并在第二个重载构造函数中使用 this(..) 调用第一个构造函数,这是最佳实践吗?

2) 是否最好使用方法调用,即 setHealthAid(10) 来设置 use 赋值的类字段,即

mHealthAid = -1;
mHasInvisibleMode = false;

没有实现 getter 和 setter 的类片段以使其简短。

public class Monster {  
private int mStrength;
private int mScareFactor;

public Monster(int strength, int scareFactor) {
setStrength(strength);
setScareFactor(scareFactor);
}

/* Getters and setters */
}

public class BigBoss extends Monster {
private int mHealthAid;
private boolean mHasInvisibleMode;

public BigBoss(int strength, int scareFactor) {
super(strength, scareFactor);
setHealthAid(-1);
setHasInvisibleMode(false);
}
public BigBoss(int strength,
int scareFactor,
int healthAid,
boolean hasInvisibleMode) {
this(strength, scareFactor);
setHealthAid(healthAid);
setHasInvisibleMode(hasInvisibleMode);
}

/* Getters and setters */
}

非常感谢您的建议,

最佳答案

1) If you have a super class Monster and you create a subclass that inherits its behaviour. Its it good practice to call super in every constructor in the subclass. What I have done below is call it once in the first overloaded constructor and in the second overloaded constructor I call the first using this(..) Is this the best practice?

您应该有一个构造函数,它采用正确实例化类所需的所有参数。在参数较少的第二个构造函数中,您应该使用 this 来调用第一个构造函数,并为缺少的参数传递默认值。喜欢:

public BigBoss(int strength, int scareFactor) {     
this(strength, scareFactor, -1, false);
}

//costructor with all required params to instantiate BigBoss properly
public BigBoss(int strength,
int scareFactor,
int healthAid,
boolean hasInvisibleMode) {
super(strength, scareFactor);
mHealthAid = healthAid;
mHasInvisibleMode = hasInvisibleMode;
}

2) Is it better to use the method calls i.e setHealthAid(10) to set the class fields of use assignment instead

您可以使用同一类中的字段 setter 来设置属性。但由于你们已经在同一个类中,所以您应该直接使用属性来设置值,即。

mHealthAid = -1;
mHasInvisibleMode = false;

这使得代码变得有点简洁,并且由于不涉及方法调用,因此您获得的性能提升很小。

关于java - 使用 'this' 关键字调用基本构造函数并使用方法调用来设置私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37064001/

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