3

Can we use stub methods for implementing interfaces ? i.e., suppose I get a message that says I must implement ServletRequestAttributeListener and HttpSessionListener - what do I need to do? Can I simply put the method signature, and use dummy values?

Caffeinated
  • 11,982
  • 40
  • 122
  • 216
  • 1
    Why would you implement an interface and not adhere to its contract properly? – alternative Sep 20 '11 at 22:39
  • @monadic - Well, in my case just to have a running system and then later I can go back and fix it. i.e, I'm putting it on the backburner, and will later come back. – Caffeinated Sep 20 '11 at 22:40
  • Yes you can create stub methods, but it almost sounds as if that class should be abstract then. – Hovercraft Full Of Eels Sep 20 '11 at 22:41
  • @monadic: particularly in the Servlet API there are this kind of interfaces like `Filter`, `ServletRequestListener`, `HttpSessionListener`, etc. You are however not necessarily required to do any business job in all methods. For example, you may not be interested in doing `init()` or in hooking on *both* `created` and `destroyed` events, etc. – BalusC Sep 20 '11 at 22:49

4 Answers4

2

I understand that you're in general talking about those XxxListener interfaces in the Servlet API.

If you're not interested in hooking on the event, just do nothing. Leave the method body empty. If necesary, add a comment like NOOP (no operation) to suppress the IDE "empty body" warning.

@Override
public void sessionDestroyed(HttpSessionEvent event) {
    // NOOP.
}

For other interfaces, it depends on their contract. I'd read their javadocs to be sure.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    @Adel yes, and using that annotation is [recommended](http://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why)! – Tyler Sep 20 '11 at 22:46
  • And it shuts up the IDE from generating warnings for unused parameters :) – BalusC Sep 20 '11 at 22:47
1

Yes you can as long as you understand the main drawback of this: the contract provided by the interface will not be satisfied by your class. This may be a problem if others end up using your code.

Finbarr
  • 31,350
  • 13
  • 63
  • 94
0

Declare your class abstract doesn't force you to implement interface's method, but you will need to do it in a subclass:

public interface bar{ public void aMethod();}
public abstract class foo implements bar{ 
     //aMethod could be not implemented here, but in the first concrete subclass of foo
}
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
0

You should consider investing some time into looking at design patterns. I think what you are looking for is The Template Method Pattern. A good book for exploring design patterns is Head First Design Patterns. It's an easy read and has some great info.

Russell Shingleton
  • 3,176
  • 1
  • 21
  • 29