如何在java中更改子类属性的默认值

时间:2017-02-27 13:59:41

标签: java constructor subclass default

这是我的主要课程,我想更改

的默认值

其余属性的默认值应如下所示:

  • hp:defaultHP
  • ip:defaultIP
  • traitCooldown:0
  • inventory:empty
  • 法术:空

具有特定值

package harrypotter.model.character;

import java.awt.Point;
import java.util.ArrayList;

import harrypotter.model.magic.Collectible;
import harrypotter.model.magic.Spell;

public abstract class Wizard {
    private String name;
    private int defaultHp;
    private int defaultIp;
    private int hp=defaultHp ;  
    private int ip=defaultIp;
    private ArrayList<Spell> spells;
    private ArrayList<Collectible> inventory;
    private Point location;
    private int traitCooldown;  

    public Wizard(String name) {            
        this.name = name;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getDefaultHp() {
        return defaultHp;
    }
    public void setDefaultHp(int defaultHp) {
        this.defaultHp = defaultHp;
    }

    public int getDefaultIp() {
        return defaultIp;
    }

    public void setDefaultIp(int defaultIp) {
        this.defaultIp = defaultIp;
    }

    public int getHp() {
        return hp;
    }
    public void setHp(int hp) {
        this.hp = hp;
    }
    public int getIp() {
        return ip;
    }
    public void setIp(int ip) {
        this.ip = ip;
    }
    public Point getLocation() {
        return location;
    }
    public void setLocation(Point location) {
        this.location = location;
    }
    public int getTraitCooldown() {
        return traitCooldown;
    }
    public void setTraitCooldown(int traitCooldown) {
        this.traitCooldown = traitCooldown;
    }
    public ArrayList<Spell> getSpells() {
        return spells;
    }
    public ArrayList<Collectible> getInventory() {
        return inventory;
    }
}

我的尝试

的子类
package harrypotter.model.character;    

public class GryffindorWizard extends Wizard implements Champion {

public GryffindorWizard(String name) {
        super(name);
        this.setHp(900);
        this.setIp(500);
        this.setTraitCooldown(0);
        this.getInventory();
        this.getSpells();
    }

    public void useTrait() {
        // TODO Auto-generated method stub

    }
 }

1 个答案:

答案 0 :(得分:0)

有趣。你打算去找:

 this.setHp(900);
 this.setIp(500);

那么,为什么不去寻找:

 this.setDefaultHp(900);
 this.setDefaultIp(500);

记录;这些作业

private int defaultHp;
private int defaultIp;
private int hp=defaultHp ;  
private int ip=defaultIp;
创建新对象时,

执行一次;所以 4 字段在创建时的值为 0 。换句话说:当你想用一些有意义的默认值初始化hp和ip时;那么考虑在那里使用非0值!