I have a class which is implementing an interface, and one of the methods is called onClick. Is there a way to implement the onClick that the interface wants but name it something else? Something like (and I’m making this up):
public void AnyMethodNameIWant() implements Interface1.onClick
Three reasons I’m asking are:
- It would be nice to look at an method signature and know that it’s
coming from an interface - To avoid ‘generic’ names like onClick that an interface may require me to have
- To distinguish between the same method names in many interfaces
Apologies if this is a fundamentally ‘bad’ question as I am new to Java.
No, you can’t. Interfaces have to be implemented by a method of the same name in Java.
You can use the
@Overrideannotation with interface implementations (as of Java 6) though, which helps to clarify that this is a method which can’t just be renamed arbitrarily.One option for your second issue might be to create an implementation class just for the purpose of forwarding on the call to a more specific method. You might want to do this as a nested or even anonymous class. I’m not sure I’d usually do this though.
EDIT: Having seen the third question – no, if you have two interfaces with the same method signature in Java, you can only provide one implementation 🙁 Oh, and if you’ve got two interfaces with the same signature but different return types, it’s even worse. You could always write a method of
Interface1 getInterface1()which returns an instance of an anonymous inner class proxying theInterface1methods onto the “main” class.