Favor Abstract Over Concrete Types

 class​ Inventory {
» LinkedList<Supply> supplies = ​new​ LinkedList();
 
»void​ stockUp(ArrayList<Supply> delivery) {
  supplies.addAll(delivery);
  }
 
» LinkedList<Supply> getContaminatedSupplies() {
  LinkedList<Supply> contaminatedSupplies = ​new​ LinkedList<>();
 for​ (Supply supply : supplies) {
 if​ (supply.isContaminated()) {
  contaminatedSupplies.add(supply);
  }
  }
 return​ contaminatedSupplies;
  }
 }

Interfaces and classes often form large type hierarchies—just look at the Java API. If you use more abstract types for variables, your code will be more flexible.

Above, you can see a part of the Inventory system. The method getContaminatedSupplies() loops through a LinkedList of Supply objects, ...

Get Java By Comparison now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.