210 likes | 302 Views
Inheritance in collections Week 16. 3.0. Main concepts to be covered. Inheritance in ArrayList objects Subtyping Substitution. The DoME example. "Database of Multimedia Entertainment" stores details about CDs and DVDs CD: title, artist, # tracks, playing time, got-it, comment
E N D
Main concepts to be covered • Inheritance in ArrayList objects • Subtyping • Substitution
The DoME example "Database of Multimedia Entertainment" • stores details about CDs and DVDs • CD: title, artist, # tracks, playing time, got-it, comment • DVD: title, director, playing time, got-it, comment • allows details of items to be printed
DoME classes top half shows fields bottom half shows methods
Database source code public class Database { private ArrayList<CD> cds; private ArrayList<DVD> dvds; public Database() { cds = new ArrayList<CD>(); dvds = new ArrayList<DVD>(); } public void addCD(CD theCD) { cds.add(theCD); } public void addDVD(DVD theDVD) { dvds.add(theDVD); }
Database source code public void list() { for(CD cd : cds) { cd.print(); System.out.println(); } for(DVD dvd : dvds) { dvd.print(); System.out.println(); } }
Critique of DoME • code duplication in CD and DVD classes • also code duplication in Database class • makes maintenance difficult/more work • introduces danger of bugs through incorrect maintenance
private ArrayList<CD> cds; private ArrayList<DVD> dvds; public Database() { cds = new ArrayList<CD>(); dvds = new ArrayList<DVD>(); } Database source code Old private ArrayList<Item> items; public Database() { items = new ArrayList<Item>(); } New
public void addCD(CD theCD) { cds.add(theCD); } public void addDVD(DVD theDVD) { dvds.add(theDVD); } Database source code Old public void addItem(Item theItem) { items.add(theItem); } New
Database source code public void list() { for(CD cd : cds) { cd.print(); System.out.println(); } for(DVD dvd : dvds) { dvd.print(); System.out.println(); } } Old public void list() { for(Item item : items) { item.print(); System.out.println(); } } New
First, we had: public void addCD(CD theCD) public void addDVD(DVD theDVD) Now, we have: public void addItem(Item theItem) We call this method with either a CD object or a DVD object as a parameter Subtyping
Subclasses and subtyping • Classes define types. • Subclasses define subtypes. • Objects of subclasses can be used where objects of supertypes are required.(This is called substitution.)
Subtyping and assignment subclass objects may be assigned to superclass variables Vehicle v1 = new Vehicle(); Vehicle v2 = new Car(); Vehicle v3 = new Bicycle();
Subtyping and parameter passing public class Database { public void addItem(Item theItem) { ... } } DVDdvd = new DVD(...); CD cd = new CD(...); database.addItem(dvd); database.addItem(cd); subclass objects may be passed to superclass parameters
Review • Inheritance can be used in collections • Variables can hold subtype objects • Subtypes can be used wherever supertype objects are expected (substitution)