I have few doubt in java, I created an interface with three methods, while implementing this interface do I need to implement all three methods contained in the interface. In my case I need to implement only one method from that interface. How to do that please.
Joined: Oct 08, 2004
Yes you have to implement all three. An interface is a contract or a promise to be able to perform certain methods. You could get away with leaving empty method braces though as long as the method looks implemented to Java. Although this is considered not to be good style.
Joined: Jul 10, 2003
thanks a Philwx, but suppose if I have 10 or more methods in my class do I need to do same as you suggest(implementing methods with empty braces)..
"Philwx", welcome to the Ranch, we appreciate your help!
But... we're pretty serious about the name rule 'round these parts. You can check them out here.
Basically we require your display name to be two words: you first name, a space, then your last name. Obviously fictitious names are not allowed. If you could please edit your profile with a valid display name we'd appreciate it.
Joined: Jul 11, 2003
Instead of implementing an empty method, would it be better for the non-implemented methods to throw NoSuchMethodException?
Or if you've more than 1 classes that partially implement this interface, would it be bettter to create an adapter class just like java.awt.event.MouseAdapter?
Any comments, Ranchers?
Joyce [ November 02, 2004: Message edited by: Joyce Lee ]
Joined: Oct 27, 2004
I'd vote against throwing the exception. If you've got an interface that has numerous methods an adapter class isn't a bad idea. If you're creating your own interface why create 10 methods if you'll only be implementing one of them? I'm no expert, but don't really understand that.
Joined: Jan 29, 2003
I've seen the exception trick done in abstract classes. That forces concrete derived classes to provide the overrides.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi