Java: type subclass in method signature

Ok Therefore, I am trying to customize the GUI for the application using the observer pattern. Standard; if the Observable update calls the update method for all its observers, passing the ComponentUpdateEvent component as follows:

public interface Observable {
 ArrayList<Observer> observers = new ArrayList<Observer>();

 public void updateObservers();

 public void addObserver(Observer observer);

 public void removeObserver(Observer observer);
}

public interface Observer {
 public void update(ComponentUpdateEvent updateEvent);
}

public abstract class ComponentUpdateEvent {
 public abstract ComponentType getComponentType();
}

I have several different components that implement Observable in the application model side. Each component type has a separate subclass of the Drawer class that implements Observer for rendering JPanel.

The problem is that I'm trying to make sure that when calling the update method of the Drawer subclass, this passed updateEvent parameter could be a subclass of ComponentUpdateEvent.

However, it is obvious if I try to do this as follows:

 @Override
 public void update(ConsoleUpdateEvent updateEvent) throws Exception {
  if (this.componentType != updateEvent.get)) {
   throw new Exception("ComponentType Mismatch.");
  }
  else {
   messages = updateEvent.getComponentState(); 
  }
 }

I get a compiler error:

The method update(ConsoleUpdateEvent) of type ConsoleDrawer must override or implement a supertype method.

. , , , ? .

+3
3

, throws Exception . , , Observer. , , Observable, , , .

+2

Observer update() throw Exception ConsoleDrawer.update(). 2 java.

throw Exception ConsoleDrawer, Observer.

0

, Java . , , .

, . , , :

generics Observer:

public interface Observer<T>

public interface Observer<T extends ComponentUpdateEvent>

, Observable.

public void addObserver(Observer<T extends ComponentUpdateEvent> observer)
-1

Source: https://habr.com/ru/post/1779452/


All Articles