Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this Java Interface flexible

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.

like image 364
John Avatar asked Dec 10 '22 00:12

John


2 Answers

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();
like image 55
Sergey Kalinichenko Avatar answered Dec 11 '22 14:12

Sergey Kalinichenko


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.

like image 44
erikxiv Avatar answered Dec 11 '22 13:12

erikxiv