Zebra.java:3:错误:调用super必须是构造函数中的第一个语句

时间:2018-01-15 21:14:11

标签: java class inheritance

所以我遇到了这个问题,super();这是方法中的第一件事,我很困惑,哪个是错的。我仍然是新的类,根据我的理解,Super基本上调用Superclass,然后Zebra类是该超类的子类。那么称Super()应该工作吗?

public abstract class Animal{
  private int hunger;

  public void hungryAnimal(int hunger){
     hunger = 0;


  }   

  public int getHunger(){
     return this.hunger;

  }

  abstract void talk();    



public class Zebra extends Animal{
   public void hungryZebra(){
      super();


   }
   public void talk(){
      System.out.println("Zebra quitly chews.");

   }


}

1 个答案:

答案 0 :(得分:0)

我认为你想要的是:

public abstract class Animal {
    private int hunger;

    public Animal() {
        this(0);
    }

    public Animal(int hunger) {
        this.hunger = hunger;
    }

    public int getHunger(){
        return this.hunger;
    }

    abstract void talk();
}

使用这样的Zebra实现:

public class Zebra extends Animal {
    public Zebra(int hunger){
        super(hunger);
    }

    public void talk(){
        System.out.println("Zebra quitly chews.");
    }
}