简体   繁体   中英

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

So I am having this issue, the 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. So would call Super() should work?

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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