如何在Java中跨多继承管理嵌套类

如何在Java中跨多继承管理嵌套类,java,inheritance,Java,Inheritance,我有一个模拟,其中有一个名为Animal的基类,以及从中派生的类,如Fox和Hare。我需要收集很多关于动物种群的信息,包括:count,malecont,adultCount等等。为了保持干净,我创建了一个静态嵌套类: public class Animal { protected static class Stats { public static int count; public static int maleCount; // a

我有一个模拟,其中有一个名为
Animal
的基类,以及从中派生的类,如
Fox
Hare
。我需要收集很多关于动物种群的信息,包括:
count
malecont
adultCount
等等。为了保持干净,我创建了一个静态嵌套类:

public class Animal {
    protected static class Stats {
        public static int count;
        public static int maleCount;
        // and many more...
    }

    private static Stats stats = new Stats();
    public static Stats getStats() {
        return stats;
    }

    protected void foo() {    //protected method using Stats
        if (getStats.maleCount > 2)
            bar();
    }
}

public class Fox extends Animal {    //Hare created similarly
    private static Stats stats = new Stats();
    public static Stats getStats() {
        return stats;
    }
}
foo
函数使用
Stats
,它应该使用正确继承类中的版本(因此,如果我们在
Fox
中调用
foo()
,它应该使用
Stats
from
Fox

现在的主要问题是

Fox.getStats().count
来自另一个类(例如,
Main
)会导致错误:

Error:(61, 42) java: main.Animal.Stats.count is defined in an inaccessible class or interface

这个问题的解决方案是什么?这种使用getter的嵌套类的方法正确吗?

如果您想从其他类访问
Stats
,它必须是公共的


受保护的访问修饰符将限制来自同一个包及其子类中的类以外的类的访问。

我已经提供了实现问题的另一个答案。让我知道你的想法。如果它偏离了你的方法太多,我很乐意修改或删除它。