-2

I have been learning about interfaces, and I'm not entirely sure when to use it. So I'm going to make up a scenario and tell me it it is a good way of using it.

Say I'm making a game, that have different characters (I was going to say classes but that would be confusing lol). I have a bunch of classes, that all extend a general hero class, which have methods like setHealth, setAttack, getHealth, getAttack, etc. but they all have a special move, but they all vary, so I could just implement an interface that has a method called specialMove, so that that the game could call on the specialMove when a button is pressed.

would this be a good example of when to use interfaces?

mooL
  • 59
  • 1
  • 3
  • 7
  • An interface describes the behavior you expect from an object passed through a "boundary" (i.e. method call) where you can be ignorant about the concrete object - when you're making a game, you might create a class to populate your screen contents and this class does not care whether he should draw a character, an object or a text message - all the class should care about is that the object being passed in should be able to be "drawn". – Smutje Jul 27 '16 at 07:19
  • 1
    @mooL Yes, perfect example. Every hero has a special attack. They are all different but they all have one. The idea is if you can define everything that the game needs to know about a character in terms of interfaces, you can add as many new characters as you like without having to modify the core game engine. – Tibrogargan Jul 27 '16 at 07:20

1 Answers1

1

The method specialMove(), which varies can be included in the interface. So whenever a class implements this interface we can identify it as having the ability to move specially, which can be done by using the instanceof operator.

Another benefit of interface is when you want to expose your code so that some third party can consume it. You will never want to show your actual coding logic rather you just provide the third party with method signatures including return types. This can be achieved with interfaces.

Sudipta Roy
  • 103
  • 1
  • 3
  • 11
  • I don't get the `instanceof` part. How would that come into play? – Fildor Jul 27 '16 at 08:54
  • I was pointing the advantage of having Interfaces, as the question initially started with "_not entirely sure when to use it_". Like in Java we have marker interface Serializable. When an object is to be serialized, the check is done whether that object `IS A` Serializable. That's when `instanceof` comes into picture. – Sudipta Roy Jul 27 '16 at 09:02