我从Parent继承了n个子类。我需要计算所有子对象,并在完成所有操作后触发侦听器。不幸的是,我收到了错误:"静态成员' childCountListener'通过实例引用访问"和"'这个'不能从静态上下文中引用"。我知道我不能使用"这个"因为我没有这个班级的对象,但我不知道如何实现这个目标。
父:
public abstract class Parent {
protected static int childCount = 0;
private static ChildCountListener childCountListener;
public Parent() {
// (...)
incrementChildCount();
}
public void doSomething() {
// (...)
decrementChildCount();
}
public static int getChildCount() {
return childCount;
}
private void incrementChildCount() {
childCount++;
}
private void decrementChildCount() {
childCount--;
if (childCount < 1) {
childCountListener.allDone();
}
}
public static void addChildCountListener(ChildCountListener childCountListener) {
this.childCountListener = childCountListener;
// Static member 'childCountListener' accessed via instance reference
// 'this' cannot be referenced form a static context
}
public interface ChildCountListener {
void allDone();
}
}
答案 0 :(得分:0)
从this
addChildCountListener
public static void addChildCountListener(ChildCountListener childCountListener) {
Parent.childCountListener = childCountListener;
}
或
public static void addChildCountListener(ChildCountListener aChildCountListener) {
childCountListener = aChildCountListener;
}