0

I have a class with an eventOccurred that does its work inside SwingUtilities.invokeLater (in order to be on the EDT). This class will be extended. I want to force anything extending this class to also put their eventOcurred work inside invokeLater and can't see how to do it. Putting final on eventOccurred in my base class won't work because I need to allow eventOccurred to be overriden.

shedhorn
  • 3
  • 2

1 Answers1

1

Can you implement a method like "doStuff()" in the base class? Then your eventOccurred method invokes this method by using the invokeLater. Then you override doStuff(), and calling eventOccurred forces it to be done on the EDT.

Like so:

class BaseClass {
    public void doStuff() {
        System.out.println("Base class do stuff");
    }

    public void EventOccurred() {
        //Put this on the EDT
        doStuff();
    }
};

class SubClass extends BaseClass {
    @Override
    public void doStuff() {
        System.out.println("Subclass do stuff");
    }
}

Then running:

BaseClass base = new BaseClass();
SubClass test = new SubClass();

base.EventOccurred();
test.EventOccurred();

Yields:

Base class do stuff
Subclass do stuff
hankd
  • 649
  • 3
  • 12
  • I'm not following. How do I force the eventOcurred in any subclasses to call doStuff? – shedhorn Nov 04 '13 at 18:51
  • I edited in some example code. Let me know if you still don't understand – hankd Nov 04 '13 at 20:17
  • OK, I'm following now. Very clever. One more thing. For this to work the eventOcurrs in every subclass must call super.eventOcurrs correct? Can I force that? – shedhorn Nov 04 '13 at 20:48
  • Never mind. Got. I put final on my BaseClass evetentOccurrs and then I'm done. Very nice. Elegant even. Thanks! – shedhorn Nov 04 '13 at 20:49
  • No problem. Are you sure you need to do that? The above code runs just fine, you don't need to override eventOccurred in the subclasses, and I'm not sure if the final is necessary. – hankd Nov 04 '13 at 20:52
  • 1
    Agree that I don't need to override it in the subclasses but I don't want anyone else to ever overrride it. If they do they are bypassing the behavior I want. – shedhorn Nov 04 '13 at 21:13
  • Very true, I thought you were saying you had to mark it as final for it to run. I agree, you probably do want it final in this case. – hankd Nov 04 '13 at 21:21