Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: substituting a subclass/subtype of a parameter when overiding a method?

So I asked this question before but I had a mistake in the code which most people picked up on, rather than the problem itself.

Anyway, I'm trying to override an interface method in a class. However, I want the type of the parameter in the overriding method to be a subclass of the type of the parameter as defined in the overriden method.

The interface is:

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

While the class that overrides this method is:

public class ConsoleDrawer extends Drawer {

//...

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

//...

}

ConsoleUpdateEvent is a subclass of ComponentUpdateEvent.

Now, I could just have the update() method in ConsoleDrawer take a ComponentUpdateEvent as a parameter and then cast it to a ConsoleUpdateEvent but I'm looking for a slightly more elegant solution if possible. Anyhelp would be appreciated. Thank you.

like image 980
carnun Avatar asked Dec 11 '10 17:12

carnun


1 Answers

Going by OOP principles, a sub-class should be usable in exactly the same way as the parent class. e.g.

Observer ob = new ConsoleDrawer();
ob.update(new ComponentUpdateEvent()); // This needs to work always.

However, if Java were to allow you to use a subtype of the parameter when overriding a method, then it would expose your code to cases where the overriding method (in the subclass) would reject the input parameter (ComponentUpdateEvent in the above case). Thus, you would never be sure whether its safe to call update() or not on an Observer reference.

Hence, the only logical solution is to accept the parent class parameter, type-check it and then cast it to the required subtype.

like image 196
user90766 Avatar answered Oct 14 '22 17:10

user90766