首页 > 解决方案 > 如何在 Java 中跨多个继承管理嵌套类

问题描述

我有一个模拟,其中我有一个名为的基类Animal和从它派生的类,例如FoxHare。我需要收集大量关于动物种群的信息,包括:count、、maleCount等等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并且它应该使用来自正确继承类的版本(所以如果我们调用foo()Fox应该使用Statsfrom Fox)。

现在的主要问题是调用

Fox.getStats().count

来自另一个类(例如Main)会导致错误:

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

什么是问题的解决方案?这种带有吸气剂的嵌套类的方法是否正确?

标签: javainheritance

解决方案


If you want to access Stats from a different class, it must be public.

The protected access modifier will restrict access from classes other than the ones in the same package and its subclasses.


推荐阅读