简单的构造函数生成错误

时间:2015-08-12 00:17:20

标签: java constructor private-methods public-method

对于战斗机类的简单构造函数,我遇到了很多错误。此外,他们似乎非法表达错误;预期错误,大部分都是。

这是我的代码:

class Fighter(String name, int health, int attack, int defense){
   //default constructor
   //input constructor

      private String name;
      private int health;
      private int attack;
      private int defense;

      private String setName(){
         this.name = name;
      }

      public String getName(){
         return name;
      }

      private int setHealth(){
         this.health = health;
      }

      public int getHealth(){
         return health;
      }

      private int setAttack(){
         this.attack = attack;
      }

      public int getAttack(){
         return attack;
      }

      private int setDefense(){
         this.defense = defense;
      }

      public int getDefense(){
         return defense;
      }
    }

我在做什么来产生所有这些错误?它与私人或公共方法有关吗?

2 个答案:

答案 0 :(得分:0)

方法进入类,而不是构造函数。我想你想要的东西,

class Fighter {
    public Fighter(String name, int health, int attack, int defense) {
        setName(name);
        setHealth(health);
        setAttack(attack);
        setDefense(defense);
    }

    private String name;
    private int health;
    private int attack;
    private int defense;

    private void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    private void setHealth(int health) {
        this.health = health;
    }

    public int getHealth() {
        return health;
    }

    private void setAttack(int attack) {
        this.attack = attack;
    }

    public int getAttack() {
        return attack;
    }

    private void setDefense(int defense) {
        this.defense = defense;
    }

    public int getDefense() {
        return defense;
    }
}

答案 1 :(得分:0)

那是你如何定义构造函数。在创建对象时调用构造函数(new Fighter())。这是一种特殊的方法,因此您只能在其中包含语句。这样:

private String setName(){
     this.name = name;
}

不是声明,所以这就是错误的原因。以上是另一种单独的方法。您应该在中定义此类内容,而不是在构造函数中定义。像这样拉出来:

public class Fighter {
    public Fighter(String name, int health, int attack, int defense) {
        setName(name);
        setHealth(health);
        setAttack(attack);
        setDefense(defense);
    }

    private String name;
    private int health;
    private int attack;
    private int defense;

    private void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    private void setHealth(int health) {
        this.health = health;
    }

    public int getHealth() {
        return health;
    }

    private void setAttack(int attack) {
        this.attack = attack;
    }

    public int getAttack() {
        return attack;
    }

    private void setDefense(int defense) {
        this.defense = defense;
    }

    public int getDefense() {
        return defense;
    }
}

现在所有方法都在构造函数之外。字段,方法和构造函数是类的组件,而不是构造函数的组件。