java - 如何在 Java 中跨多个继承管理嵌套类
问题描述
我有一个模拟,其中我有一个名为的基类Animal
和从它派生的类,例如Fox
和Hare
。我需要收集大量关于动物种群的信息,包括: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
应该使用Stats
from Fox
)。
现在的主要问题是调用
Fox.getStats().count
来自另一个类(例如Main
)会导致错误:
Error:(61, 42) java: main.Animal.Stats.count is defined in an inaccessible class or interface
什么是问题的解决方案?这种带有吸气剂的嵌套类的方法是否正确?
解决方案
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.
推荐阅读
- android - 为什么 PowerMockito 会抛出 TooManyActualInvocations?
- django - Django下拉列表不保存价值
- java - 如何在 Spring Boot 服务中使用多态性?
- javascript - 使用 useEffect 时超出最大深度
- ios - 在 iOS 上设置 Firebase FCM 时出错:Flutter
- git - git-receive-pack 使用双引号而不是单引号,而 git 使用单引号调用它
- ruby - 如何组织您的自定义文件目录(Rails 6.1.3.2)?
- javascript - discord.js 中的 MongoDB 缓存
- c - Windows Api,COM口:接收后传输数据
- regex - 替换@之前的所有字符