Search code examples
javaoopdesign-patternsinterfacecomposition

using interface and composition in java - reuse code with different variables


I have a problem during trying to do reuse code. I want to use main interface with two classes, but some of the methods have same implements, so I decided to use compostion. I mean, to declare instance of the "a" class and do on the method:

void do_some()
a.do_some()

the problem is that the function related to some data members. for example:

 public class Locker implements GeneralStorage {
    private final int current_capacity;

  public int getAvailableCapacity(){
        return current_capacity;
      }
}

public class LongTermStorage implements GeneralStorage {
    private final int current_capacity;
    private Locker locker=New Locker();
       public int getAvailableCapacity(){
           return locker.getAvailableCapacity

what can I do? (I want to return LongTermStorage.current_capacity)


Solution

  • You can do so, but it'd be better if you create an instance for composition at your constructor. So it would be like this:

    public class Locker implements GeneralStorage {
      private final int current_capacity;
    
      public int getAvailableCapacity(){
        return current_capacity;
      }
    }
    
    public class LongTermStorage implements GeneralStorage {
      private Locker locker;
    
      public LongTermStorage() {
        locker = new Locker();
      }
    
      public int getAvailableCapacity(){
        return locker.getAvailableCapacity();
      }
    }
    

    So, you will reuse Locker methods and also its props.