Override method in inherited interface with subtype with generics

I have the following hierarchy in java:

interface ObserverA {}

interface A {
  void method1();
  addObserver(Observer o);
}

And I want to expand it as follows:

interface ObserverB extends ObserverA{}

interface B extends A {
   void method2();
   addObserver(ObserverB  o);
}

so that the method addObserver() Boverrides the same method in A. Since it does not work, implementations Bwill need to implement both versions addObserver(), I will not have only one.

Is it possible to do this in a smart way that does not require parameterization Aas:

interface A<O extends Observer> { 
    addObserver(O o);
}

Welcome Hackish Solutions!

+5
source share
3 answers

You cannot narrow down the types of method parameters in subinterfaces or subclasses. You can only expand them, as subtype implementations should be able to fulfill a supertype contract.

, .

+4

- , , , . :

public interface Observer<T> {
    void addObserver(T t);
}

public class First implements Observer<First> {
    @Override
    public void addObserver(First t) {
    }
}

public class Second implements Observer<Second> {
    @Override
    public void addObserver(Second t) {
    }
}

, , , . themselved, , Observer<Frist>, Observer<Integer> .

, .

interface ObserverA {}

interface A<T> {
    void method1();
    void addObserver(T o);
}

interface ObserverB extends ObserverA {}

interface B extends A<ObserverB> {
    void method2();
}
+2

-

interface ObserverA {}

interface A {

    <T extends ObserverA> void addObserver(T o);
}

-

interface ObserverB extends ObserverA{}

interface B extends A{

    // do nothing, or omit this interface entirely.

}

, ObserverA addObserver.

, .

, . , , addObserver, ObserverA ObserverA. ObserverB ObserverA, ObserverA ObserverB .

From your explanation, it seems that you should create two different interfaces without any hierarchical relationship between them. They seem to be disconnected because you want to provide an implementation only for the second method, while avoiding the first. Thus, instead of forcing yourself to provide a method implementation from the first interface, you should separate them. For this, there is also the principle of OOP - the principle of separation of circuits .

+1
source

All Articles