1

In an interface, I have a method that is okay to use in one implementation, but shouldn't be used in another. I'm thinking of throwing an exception if somebody were to use that method in that particular implementation. (which is not to say it's easy to accidentally come across that exception)

To be more specific, the method is getPlayer(String), which gets a Player by name. Player is a client connected to a server, however in my 2nd implementation, it would be impossible to get any connected clients, as the 2nd implementation represents other (cached and technically offline) servers which are stored in a list somewhere.

Any help is appreciated. Let me know if code pastes would better help describe the nature of the scenario.

octopod
  • 824
  • 2
  • 10
  • 23
  • 1
    Sounds like a job for composition, not inheritance? – George Stocker Nov 21 '14 at 12:24
  • Yeah, sounds like composition would fit better. It is very likely that something is wrong in your model if you want a given method to be used only in a few implementations of the interface. – Gabriel Oliveira Nov 21 '14 at 12:27
  • I could maybe split the interface into an "OnlineServer" and "OfflineServer", where only OnlineServer contains the `getPlayer(String)` method, though I've the feeling that isn't what you guys mean by composition. – octopod Nov 21 '14 at 12:31

2 Answers2

4

I'd throw an IllegalStateException

Signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

or if your implementation simply doesn't support it, you could go also with UnsupportedOperationException

Thrown to indicate that the requested operation is not supported.

peter
  • 14,348
  • 9
  • 62
  • 96
1

It is mandatory to implement all the methods of an interface. The accepted answer of this question might help.

Community
  • 1
  • 1
Alok Dubey
  • 419
  • 4
  • 13
  • I don't disagree; All the methods of the interface are implemented, but some of them just wouldn't work in the context of the 2nd implementation. – octopod Nov 21 '14 at 12:35