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:
public interface Box {
public void open();
public void close();
}
public interface LockableBox extends Box {
public void lock();
public void unlock();
}
public interface MutableBox extends Box {
public void putItem(int item);
public void removeItem(int item);
}
Now your boxes can implement an interface from the hierarchy that fits your design.
public class RedBox implements LockableBox {
public void open() {}
public void close() {}
public void lock() {}
public void unlock() {}
}
public class BlueBox implements MutableBox {
public void open() {}
public void close() {}
public void putItem(int item) {}
public void removeItem(int item) {}
}
With a hierarchy in place, you can continue programming to the interface:
MutableBox mb = new BlueBox();
mb.putItem(123);
LockableBox lb = new RedBox();
lb.unlock();
The new classes implementing the Box interface will only need to implement the methods in the Box interface, not any other methods in other classes implementing the Box interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With