Search code examples
javaoopinterfaceclass-designobject-oriented-analysis

how to create an interface around classes that already exist but cannot be modified in java


Suppose I already have 2 classes in my code:

class SomeOrder {
  String getOrderId() { return orderId; }
}

class AnotherOrder {
  String getOrderId() { return orderId; }
}

How to create an interface around both these classes which is:

interface Order {
    String getOrderId();
}

Ideally, I would modify the code so that SomOrder implements Order and AnotherOrder implements Order but the catch here is that they belong in a package that I cannot control or edit (i.e. they come from an external jar).

My algorithm currently looks like this:

void sorter(List<SomeOrder> orders) {
    ... <custom sort logic> ...
    someOrder.getOrderId();
}

void sorter(List<AnotherOrder> orders) {
    ... <custom sort logic> ...
    someOrder.getOrderId();
}

With a single interface I can write:

void sorter(List<Order> orders) {
        ... <custom sort logic> ...
        order.getOrderId();
}

Solution

  • You can use adapter classes:

    class SomeOrderAdapter implements Order {
        private SomeOrder delegate;
    
        @Override
        public String getOrderId() {
            return delegate.getOrderId();
        }
    }
    

    and similar for AnotherOrder.