Is it okay for two or more interfaces to have the same methods?

Nicolás Vera :

I'm making a simple game with Java, and I have this doubt.

Suppose that there's an interface for every game character

public interface Entity{
   Vector2 getPosition();
   /* More methods...*/
}

Then I want to create an interface called Automata implemented by every class that uses AI stuff (This could be a special case of Entity, but I thought it separately because of reusability)

public interface Automata{
  Vector2 getPosition(); // The AI stuff needs to know this
  /* More methods needed for AI (some may also be the same as Entity)... */
}

I think this promotes modularity, because every interfaces describes its methods without worrying about the existence of other interfaces, but while I was writing this I felt like I was repeating myself, so is having this two (or may be more) interfaces with same methods something bad ?

Nicholas K :

If there is something common between both interfaces then maybe you can define a parent interface and then Entity and Automata could extend it.

Let me illustrate it below :

interface AI {
    Vector2 getPosition();
}

interface Entity extends AI { }
interface Automata extends AI { }

This way any other interface that is a part of AI would not need to explicitly add another method but instead just extend AI

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=75435&siteId=1