Since you have had a java-8-tag, you have access to the default
keyword for an interface
method, which is new since Java 8.
So you could modify it to something along the lines of:
public interface Animal{
public void operationWalk();
default void doSomething(){
// Your code here
}
}
This default
method can be added to the interface, without having to add the implementations to your child classes that use this interface.
Note that default
methods can still be overwritten in the child classes if you choose to. If you never want to overwrite this method, you could use a static
method in the interface instead. Here a bit more info about default
vs static
methods in interfaces.
If you are using a version prior to Java 8, I'm afraid the only options you have are:
1) If you need this new method in each of the 100+ classes that implement this interface, you'll have to add this new method to your interface and implement the new method in each of those classes.
2) If you need this new method in only a few of the 100+ classes, you can create a new interface and implement this new interface only in those classes, including the implementation of the method.
3) If you need a standard method that is the same for each child class, as your question suggests, you can create an abstract class
implementing the Animal-interface
with the implementation of the new method, and then change each of the 100+ classes to extend this abstract
class. You'd still have to modify each of those classes, but then you do have a default implementation for your new method in Java 7. Note that all classes can only extend a single abstract
class, so if any of your classes implementing the Animal
-interface are already extensions of other classes, this option isn't possible.
Although I would personally check if you could update to Java 8 (or higher) instead, since it has the default
keyword for interfaces
that you need for the best solution in this case. Since Java 11 is already released, it's not a bad idea to update to a newer Java version anyway.