Java的。抽象类儿童计数器听众

时间:2015-05-04 18:11:00

标签: java

我从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();
}
}

1 个答案:

答案 0 :(得分:0)

this

中删除addChildCountListener
public static void addChildCountListener(ChildCountListener childCountListener) {
    Parent.childCountListener = childCountListener;
}

public static void addChildCountListener(ChildCountListener aChildCountListener) {
    childCountListener = aChildCountListener;
}