简体   繁体   English

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

[英]Zebra.java:3: error: call to super must be first statement in constructor

So I am having this issue, the super(); 所以我遇到了这个问题,super(); is the first thing in the method, I am confused as to whats wrong. 是方法的第一件事,我对什么地方不对感到困惑。 I am still new to classes and from my understanding Super basically calls the Superclass and then the Zebra class is a subclass of that superclass. 我仍然是类的新手,据我所知,Super基本上称为Superclass,然后Zebra类是该超类的子类。 So would call Super() should work? 那么调用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.");

   }


}

I think what you wanted is this: 我认为您想要的是:

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();
}

With the Zebra implemantation like this: 通过这样的Zebra实现:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM