Caffeinated
Caffeinated

Reputation: 12474

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 HttpSessionListener - what do I need to do? Can I simply put the method signature, and use dummy values?

Upvotes: 3

Views: 295

Answers (4)

BalusC
BalusC

Reputation: 1108692

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.

Upvotes: 2

Russell Shingleton
Russell Shingleton

Reputation: 3196

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.

Upvotes: 0

Heisenbug
Heisenbug

Reputation: 39164

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
}

Upvotes: 0

Finbarr
Finbarr

Reputation: 32126

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.

Upvotes: 1

Related Questions