I have a java class which fires custom java events. The structure of the code is the following:
public class AEvent extends EventObject { ... } public interface AListener extends EventListener { public void event1(AEvent event); } public class A { public synchronized void addAListener(AListener l) { .. } public synchronized void removeAListener(AListener l) { .. } protected void fireAListenerEvent1(AEvent event) { .. } }
Everything works correctly, but I’d like to create a new subclass of A (call it B), which may fire a new event. I’m thinking of the following modification:
public class BEvent extends AEvent { ... } public interface BListener extends AListener { public void event2(BEvent event); } public class B extends A { public synchronized void addBListener(BListener l) { .. } public synchronized void removeBListener(BListener l) { .. } protected void fireBListenerEvent2(AEvent event) { .. } }
Is this the correct approach? I was searching the web for examples, but couldn’t find any.
There are a few things I don’t like in this solution:
BListenerhas two methods one usesAEventthe other usesBEventas a parameter.Bclass both hasaddAListenerandaddBListenermethods. Should I hide addAListener with private keyword? [UPDATE: it’s not possible to hide with private keyword]- Similar problem with
fireAListenerEvent1andfireBListenerEvent1methods.
I’m using Java version 1.5.
I don’t see a reason why
BListenershould extendAListener.Do you really want to force everyone interested in
Bevents to also implementevent1()?Also you can’t add
addAListener(), since a derived class can not reduce the visibility of a method that’s present in the parent class. Also, you shouldn’t need to, or you would violate the Liskov substitution principle (every B must be able to do everything an A can do).And as a last remark, I’d make the
fire*()methods protected. There’s usually no reason at all to keep them public and reducing the number of public members keeps your public interface clean.