我该如何解决这个堆栈溢出错误?

时间:2016-10-26 10:32:48

标签: java

    public Dog[] dogList =
    {
        new Dog(1, 2, "Bacon"),
        new Dog(3, 4, "Cheese"),
        new Dog(8, 6, "Steak"),
        new Dog(5, 6, "Lamb"),
        new Dog(12, 14, "Caviar")
    };

每当我运行程序时,我都有一个StackOverflowError。

    System.out.println(new Dog(2, 3, "hi").compareTo(new Dog(1, 2, "a")));

我通过该代码运行它。 狗类源代码:

package Luka;

import java.util.Arrays;

public class Dog extends Animal implements Comparable<Dog>{



    public void eat(String food)
    {
        System.out.println("The dog enjoyed his meal of " + food);
    }
    public int compareTo(Dog other)
    {   
        if(this.age < other.age)
        {
            int returnNum = -1;
            return returnNum;
        }
        else if(this.age > other.age)
        {
            int returnNum = 1;
            return returnNum;
        }
        else
        {
            int returnNum = 0;
            return returnNum;
        }
    }
    public String toString(int weight,int age,String foodType)
    {
        return "The dog weighs "+weight+", is "+age+" years old, and eats "+foodType+" for dinner.";
    }
    public Dog(int weight, int age, String foodType)
    {
        this.weight = weight;
        this.age = age;
        this.foodType = foodType;
    }
        public Dog[] dogList =
        {
            new Dog(1, 2, "Bacon"),
            new Dog(3, 4, "Cheese"),
            new Dog(8, 6, "Steak"),
            new Dog(5, 6, "Lamb"),
            new Dog(12, 14, "Caviar")
        };
}

1 个答案:

答案 0 :(得分:1)

每当你有一个变量初始值设定项时,初始化变量的代码就会有效地添加到你的构造函数中。

例如:

public Dog[] dogList = { new Dog(1, 2, "Bacon"), ... };

public Dog(int weight, int age, String foodType) {
  this.weight = weight;
  this.age = age;
  this.foodType = foodType;
}

相当于:

public Dog[] dogList;

public Dog(int weight, int age, String foodType) {
  this.dogList = { new Dog(1, 2, "Bacon"), ... };

  this.weight = weight;
  this.age = age;
  this.foodType = foodType;
}

所以你无条件地调用Dog构造函数中的Dog构造函数。

dogList课程中移除Dog,或将其设为static

相关问题