将 parent 作为 child 引用作为参数传递给函数,该函数接受 children 作为 Java 中的参数

Passing parent as child reference as an argument to a function that accepts the children as argument in Java

也许标题不正确,所以我会更准确地解释我需要做什么。 我重写了一个“Observer-Observable" interface 让我的 Observer 根据我收到的各种通知 Events 对方法 update(Observable o, Object arg) 进行 重载 写道(我没有使用 java.awt 中的那些)。 例如

public interface RewrittenObserver{
    public void update(RewrittenObservable o, EventChild1 event);
    public void update(RewrittenObservable o, EventChild2 event);
    public void update(RewrittenObservable o, EventChild3 event);
    .....
}

我程序中的每个函数 return 都是一个 EventChild(Event 是抽象的 class 父亲)。

public Event returnMeAnEvent(){... return new EventChild1()};

并且 RewrittenObservable 通知它调用观察者的更新。

public abstract class RewrittenObservable {
     private RewrittenObserver observer;
     /*....Constructor definitions...*/
     public void notify(EventChild1 event){
         observer.update(this, event);
     }
}

我正在使用 RewrittenObservable class

的扩展
public class ObservableChild extends RewrittenObservable{
    ....
    public void doSomething(){... notifyChild(returnMeAnEvent())};
    public void notifyChild(EventChild1 event){
      super.notify(event);
}

问题是 ObservableChild class 无法调用 super.notify(event) 因为 return returnMeAnEvent() 函数是一个抽象类型(虽然我实际上是 returning 一个 child 引用),所以它实际上搜索

public void notify(Event event){
}

我在理解继承方面有问题吗?你能建议我解决这个问题吗?不知道是@Override ObservableChild class 中的notify 方法好还是用super.notify() 方法好[=] =31=]

您可能想按如下方式更改 RewrittenObservable

public abstract class RewrittenObservable {
     // ...
     public void <T extends Event> notify(T event) {
         observer.update(this, event);
     }
}

请注意,这可能不适用于 RewrittenObserver 的当前结构,因为重载可能不明确。无论如何,您可能想要一个通用接口,而不是在适当的实现中专门处理事件。

这也大大简化了 RewrittenObserver

的实现
public interface RewrittenObserver<T extends Event> {
     public void update(RewrittenObservable o, T event);
}

对于特定的 child 类 然后使用:

public class EventChild1Observer implements RewrittenObserver<EventChild1> {
    @Override
    public void update(RewrittenObservable o, EventChild1 event) {
        // implementation here
    }
}

旁注:this codereview-question 您可能对其中的答案感兴趣。