I would create an extension of your interface for only the classes that need the additional methods...
public interface BaseInterface {
public int exampleMethod();
}
public interface ExtendedInterface extends BaseInterface {
public int anotherMethod();
}
The thousands of classes already implement BaseInterface
. For the classes that need the extra method, you change them to implement ExtendedInterface
.
If your objects are stored in a collection such as a BaseInterface[]
array, this still works because objects of type ExtendedInterface
are also objects of type BaseInterface
, so they can still be stored in the same common collection.
For example, this is still perfectly valid...
BaseInterface[] objects = new BaseInterface[2];
objects[0] = new ClassThatImplementsBaseInterface();
objects[1] = new ClassThatImplementsExtendedInterface();
However, if you need to access the new method of the ExtendedInterface
, but the object is stored in a BaseInterface
collection, you'll need to cast it into an ExtendedInterface
before you can use it...
BaseInterface[] objects = new BaseInterface[1];
objects[0] = new ClassThatImplementsExtendedInterface();
if (objects[0] instanceof ExtendedInterface){
// it is an ExtendedInterface, so we can call the method after we cast it
((ExtendedInterface)objects[0]).anotherMethod();
}
else {
// it is a BaseInterface, and not an ExtendedInterface
}
This may or may not be suitable, depending on your usage.
If you really need all your thousands of objects to implement the new method, you'll have to add the method to the BaseInterface
and then use a feature of your IDE or text editor to implement the method in all your classes. For example, you could open them all in a text editor and do a find-replace to find something thats common to each class, and replace it with the common code + the default code for the new method. Pretty quick and painless. I'm sure that some IDEs would probably also automatically add the method declaration to all inheriting classes, or at least have an option to do this in a right-click menu.