Jon Merritt Jon Merritt - 3 months ago 21
Android Question

Should an interface contain its own callback class?

If I have an interface with multiple callbacks, that I'd like to be used either as a complete set or individually. Can I simply create the needed class inside the interface? Or should I make it static and move it to another class?

Example of what I mean in code:

public interface SomeChangeListener {

void OnSomeChangeA();

void OnSomeChangeB();

class SomeCallback implements SomeChangeListener {

public void OnSomeChangeA() {}

public void OnSomeChangeB() {}

This works well, I'm only concerned about any flaws in it, that will cause issues at some point. Memory leaks etc...

Any tips would be appreciated.


Putting a class definition into an interface ... should not cause a memory leak. Like: never.

Or in other words: if you manage to put down a class definition that leads to some memory leak, than that leak is caused by things your code is doing. Not by the fact that it is part of some byte code belonging to some class here or there!

Thus the flaw that really matters here is: typically, interfaces are used to create an abstraction from concrete implementations. Putting one implementation directly into your interface somehow contradicts that goal! See here for example.

Long story short: you can do that; but I think it carries a certain "bad design" smell.