Kevin Rave
Kevin Rave

Reputation: 14456

Liskov Substitution Principle - Am I violating it here?

I am still trying to understand LSP. From what I understand so far, Subclasses / Subtypes should be able to substitute Baseclass / Main type and the program should work intact.

I have the following...

  abstract class Warehouse<T> {
      private StockLoader<T> loader;
      private List<T> stock;

      protected setStockLoader(StockLoader loader) {
             this.loader = loader;
      }

      protected List<T> getStock() {
           return stock;
      }

      public void load() {
         stock = loader.load();
      }

      abstract showStock();
  }

 class WheatWH extends Warehouse<Wheat> {
     @Override
     public void showStock() {
         // Print stocck with getStock() returns Wheat;
     }
 }

 class RiceWH extends Warehouse<Rice> {
     @Override
     public void showStock() {
         // Print stocck with getStock() returns Rice;
     }
 }


  interface List<T> StockLoader<T>() {
      public List<T> load();     
  }

  class PlainStockLoader implements StockLoader<Wheat>{
      public List<Wheat> load() {
             //Code
      }
  }

  class Rice {
      .....
  }

  class Wheat {
      ....
  }

Does it violate LSP? If not, what would violate LSP in the above progream? In addition, does this violate any other principle? Can this be improved in any other way?

Upvotes: 0

Views: 344

Answers (1)

NAMS
NAMS

Reputation: 991

What you have looks perfectly fine. The goal here would be to have an implementation such that you could do something like:

Warehouse<Wheat> wheat = new WheatWH();
Warehouse<Rice> rice = new RiceWH();

And then be able to call methods from the Warehouse class on wheat and rice regardless of which subclass they are. The code you have so far does this perfectly, so I would say you are definitely on the right track.

Upvotes: 1

Related Questions