Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is there a shortcut way to implement interfaces?

Tags:

java

interface

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?

like image 889
Caffeinated Avatar asked Dec 07 '25 06:12

Caffeinated


2 Answers

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

  • http://download.oracle.com/javaee/6/api/javax/servlet/package-summary.html
  • http://download.oracle.com/javaee/6/api/javax/servlet/http/package-summary.html

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.

like image 109
BalusC Avatar answered Dec 08 '25 20:12

BalusC


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.

like image 28
Finbarr Avatar answered Dec 08 '25 20:12

Finbarr