开发者

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

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


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.


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.


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
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜