Download presentation
Presentation is loading. Please wait.
Published byChad Harper Modified over 9 years ago
1
Inheritance in collections Week 16 3.0
2
Main concepts to be covered Inheritance in ArrayList objects Subtyping Substitution
3
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
4
DoME objects
5
DoME classes top half shows fields bottom half shows methods
6
DoME object model
7
Class diagram
8
public class Database{ private ArrayList cds ; private ArrayList dvds ; public Database() { cds = new ArrayList (); dvds = new ArrayList (); } public void addCD(CD theCD) { cds.add(theCD); } public void addDVD(DVD theDVD) { dvds.add(theDVD); } Database source code
9
public void list() { for(CD cd : cds) { cd.print(); System.out.println(); } for(DVD dvd : dvds) { dvd.print(); System.out.println(); } Database source code
10
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
11
Using inheritance
12
private ArrayList items; public Database() { items = new ArrayList (); } Old New Database source code private ArrayList cds; private ArrayList dvds; public Database() { cds = new ArrayList (); dvds = new ArrayList (); }
13
public void addItem(Item theItem) { items.add(theItem); } Old New Database source code public void addCD(CD theCD) { cds.add(theCD); } public void addDVD(DVD theDVD) { dvds.add(theDVD); }
14
public void list() { for(Item item : items) { item.print(); System.out.println(); } Old 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(); }
15
Subtyping First, we had: public void addCD(CD theCD) public void add DVD ( DVD the DVD ) Now, we have: public void addItem(Item theItem) We call this method with either a CD object or a DVD object as a parameter
16
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.)
17
Subtyping and assignment Vehicle v1 = new Vehicle();Vehicle v2 = new Car();Vehicle v3 = new Bicycle(); subclass objects may be assigned to superclass variables
18
Subtyping and parameter passing public class Database { public void addItem(Item theItem) {... } DVD dvd = new DVD(...); CD cd = new CD(...); database.addItem(dvd); database.addItem(cd); subclass objects may be passed to superclass parameters
19
Object diagram
20
Class diagram
21
Review Inheritance can be used in collections Variables can hold subtype objects Subtypes can be used wherever supertype objects are expected (substitution)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.