I have this Java Interface:
public interface Box {
public void open();
public void close();
}
This interface is extended by this class:
public class RedBox implements Box {
public void open() {
}
public void close() {
}
}
The problems is that I’m looking to add other classes in the future that will also implement the Box Interface. Those new classes will have their own methods, for example one of the classes will have a putInBox() method, But if I add the putInBox() method to the Box Interface, I will also be forced to add an empty implementation of putInBox() method to the previous classes that implemented the Box Interface like the RedBox class above.
I’m adding putInBox() to the Box Interface because there is a class Caller that takes an object of classes that implemented the Box Interface, example:
public class Caller {
private Box box;
private int command;
public Caller(Box b) {
this.box = b;
}
public void setCommandID(int id) {
this.command = id;
}
public void call() {
if(command == 1) {
box.open();
}
if(command == 2) {
box.close();
}
// more commands here...
}
}
Caller c = new Caller(new RedBox());
c.call();
How do I implement the Box Interface in the new classes without been forced to add empty implementation of new methods to each of the previous classes that implemented the Box Interface.
You are not limited to a single interface – you can build an entire hierarchy! For example, you can make these three interfaces:
Now your boxes can implement an interface from the hierarchy that fits your design.
With a hierarchy in place, you can continue programming to the interface: