Chapter 8:
![]()
Chapter 8 |
Chapter 7 introduced the design of classes. Chapter 8 examines a fundamental object-oriented construct for reusing code: inheritance.
| inheritance - defines one class as an extension on another. |
super (parent) class - The class that
is extended with additional fields and methods. TicketMachine is the
super or parent class.
sub (child) class - The class that
inherits all fields and methods of the super class. BusTicketMachine is
the subclass of TicketMachine.
private - Subclasses inherit but cannot access private methods or fields.
public - TicketMachine methods
that are public can be called as internal methods (i.e. called on a
BusTicketMachine object). Public fields are accessible in
subclass.
constructor - TicketMachine
constructors can be called as super followed by any normal parameters.
The TicketMachine(int ticketCost) constructor is called by
super(cost) in the BusTicketMachine( int cost, String bus, String
stops ) constructor below.
over-riding methods - The
printTicket() method is defined in both classes, the definition used is the
closest class. BusTicketMachine objects call BusTicketMachine
printTicket() method, TicketMachine objects call TicketMachine
printTicket() method.
super - Over-riding methods as with printTicket() blocks access to inherited methods. To call a super class method, precede the method call with super.
|
|
Exercise 1 - Inheritance
- Suppose that we have created a BusTicketMachine by:
BusTicketMachine btm = new BusTicketMachine( 50, "Number 3", "4th St. - Mall - Airport" );
Trace the execution of the constructors.
- Trace the execution of:
btm.insertMoney( 75 );
- Trace the execution of:
btm.printTicket( );

Database of CD's and video's.
- The database will store two collections, one for CD's and the other for video's.
- The class fields are listed in the object diagram for each at right.
Exercise 2 - Need for Inheritance
- How are the CD and Video fields the same?
- How are the CD and Video fields different?
- What types are each of the fields?
| UML - Unified Modeling Language, a notation for designing and understanding object oriented systems. |
Some of the data fields and methods given in UML form that are likely needed to model a collection of CD's and video's.
The figure at right lists both the fields (top) and methods (bottom) for the CD and Video class.
Note the common fields and methods. We may determine later that others may be needed but this shows the commonality between the two classes.
We would like to avoid duplication, inheritance can be used when the child classes are cohesive with the parent.
The database holds the CD and Video collections separately as an ArrayList object for each.
The object diagram of the database
coarsely illustrates the database object with four CDs and four Videos.
Exercise 3 - Need for Inheritance
- How are CD and Video methods the same?
- How are CD and Video fields the same?
- How are the CD and Video methods different?
- How are the CD and Video fields different?
| public class Video { private String title; private String director; private int playingTime; private boolean gotIt; private String comment; public Video(String theTitle, String theDirector, int time) { title = theTitle; director = theDirector; playingTime = time; gotIt = false; comment = "<no comment>"; } public void setComment(String comment) { this.comment = comment; } public String getComment() { return comment; } public void setOwn(boolean ownIt) { gotIt = ownIt; } public boolean getOwn() { return gotIt; } public void print() { System.out.print("video: " + title + " (" + playingTime + " mins)"); if(gotIt) { System.out.println("*"); } else { System.out.println(); } System.out.println(" " + director); System.out.println(" " + comment); } } |
public class CD { private String title; private String artist; private int numberOfTracks; private int playingTime; private boolean gotIt; private String comment; public CD(String theTitle, String theArtist, int tracks, int time) { title = theTitle; artist = theArtist; numberOfTracks = tracks; playingTime = time; gotIt = false; comment = "<no comment>"; } public void setComment(String comment) { this.comment = comment; } public String getComment() { return comment; } public void setOwn(boolean ownIt) { gotIt = ownIt; } public boolean getOwn() { return gotIt; } public void print() { System.out.print("CD: " + title + " (" + playingTime + " mins)"); if(gotIt) { System.out.println("*"); } else { System.out.println(); } System.out.println(" " + artist); System.out.println(" tracks: " + numberOfTracks); System.out.println(" " + comment); } } |
Database class
- The database values are not stored on a file so are lost when program closed.
- There is no user interface except using BlueJ.
| import java.util.ArrayList; import java.util.Iterator; public class Database { private ArrayList cds; private ArrayList videos; public Database() { cds = new ArrayList(); videos = new ArrayList(); } public void addCD(CD theCD) { cds.add(theCD); } public void addVideo(Video theVideo) { videos.add(theVideo); } public void list() { // print list of CDs for(Iterator iter = cds.iterator(); iter.hasNext(); ) { CD cd = (CD)iter.next(); cd.print(); System.out.println(); // empty line between items } // print list of videos for(Iterator iter = videos.iterator(); iter.hasNext(); ) { Video video = (Video)iter.next(); video.print(); System.out.println(); // empty line between items } } } |
|
The figure at right reflects the DoME application after four CDs and four Videos have been entered into the Database object.
| Exercise 4 - DoME
In BlueJ
|
| public class Video { public void print() { System.out.print("video: " + title + " (" + playingTime + " mins)"); if(gotIt) { System.out.println("*"); } else { System.out.println(); } System.out.println(" " + director); System.out.println(" " + comment); } |
public class CD { public void print() { System.out.print("CD: " + title + " (" + playingTime + " mins)"); if(gotIt) { System.out.println("*"); } else { System.out.println(); } System.out.println(" " + artist); System.out.println(" tracks: " + numberOfTracks); System.out.println(" " + comment); } } |
| inheritance - defines one class as an extension on another. |
Item class code
| public class Item { private String title; private int playingTime; private boolean gotIt; private String comment; public Item(String theTitle, int time) { title = theTitle; playingTime = time; gotIt = false; comment = ""; } public void setComment(String comment) { this.comment = comment; } public String getComment() { return comment; } public void setOwn(boolean ownIt) { gotIt = ownIt; } public boolean getOwn() { return gotIt; } public void print() |
CD class code
|
Before inheritance |
After inheritance |
| public class CD { private String title; private String artist; private int numberOfTracks; private int playingTime; private boolean gotIt; private String comment; public CD(String theTitle, String theArtist, int tracks, int time) { title = theTitle; artist = theArtist; numberOfTracks = tracks; playingTime = time; gotIt = false; comment = "<no comment>"; } public void setComment(String comment) { this.comment = comment; } public String getComment() { return comment; } public void setOwn(boolean ownIt) { gotIt = ownIt; } public boolean getOwn() { return gotIt; } public void print() { System.out.print("CD: " + title + " (" + playingTime + " mins)"); if(gotIt) { System.out.println("*"); } else { System.out.println(); } System.out.println(" " + artist); System.out.println(" tracks: " + numberOfTracks); System.out.println(" " + comment); } } |
public class CD extends Item { private String artist; private int numberOfTracks; public CD(String theTitle, String theArtist, int tracks, int time) { super(theTitle, time); artist = theArtist; numberOfTracks = tracks; } public String getArtist() { return artist; } public int getNumberOfTracks() { return numberOfTracks; } public void print() { System.out.println(" " + artist); System.out.println(" tracks: " + numberOfTracks); } } ![]() |
Video class code
|
Before inheritance |
After inheritance |
| public class Video { private String title; private String director; private int playingTime; private boolean gotIt; private String comment; public Video(String theTitle, String theDirector, int time) { title = theTitle; director = theDirector; playingTime = time; gotIt = false; comment = "<no comment>"; } public void setComment(String comment) { this.comment = comment; } public String getComment() { return comment; } public void setOwn(boolean ownIt) { gotIt = ownIt; } public boolean getOwn() { return gotIt; } public void print() { System.out.print("video: " + title + " (" + playingTime + " mins)"); if(gotIt) { System.out.println("*"); } else { System.out.println(); } System.out.println(" " + director); System.out.println(" " + comment); } } |
public class Video extends Item
{ private String director; public Video(String theTitle, String theDirector, int time) { super(theTitle, time); director = theDirector; } public String getDirector() { return director; } public void print() } |

Exercise 5 - Inheritance hierarchies
- Extend the hierarchy diagram at right to include jazz, blues, R&R, country western and rap.
- Extend the hierarchy diagram at right to include musicals, science fiction, soap operas, TV shows and comedy.
| Item | Video | CD |
| public class Item { private String title; private int playingTime; private boolean gotIt; private String comment; public Item(String theTitle, int
time) public void print() |
public class Video extends
Item { private String director; public void print() { System.out.println(" " + director); } public String getDirector() { return director; } } |
public class CD extends
Item { private String artist; private int numberOfTracks; public void print() { System.out.println(" " + artist); System.out.println(" tracks: " + numberOfTracks); } public String getArtist() { return artist; } public int getNumberOfTracks() { return numberOfTracks; } } |

Exercise 6 - Inheritance and access rights In BlueJ
- Open project Chapter08/dome-v2
- Create a CD object.
- Call a public inherited method such as setComment().
- Open class Video
- Remove the extends Item
- What is the result of compiling Video?
- Why?
- Restore the extends Item
| Superclass constructor - Subclass constructor must call super-class constructor as the first statement. |
| Item | Video | CD |
|
|
|
Exercise 7 - Inheritance and initialization In your head
- Trace the execution of:
- CD mycd = new CD("Quacker", "Duck", 300, 10000);
- Trace the execution of:
- Video myvideo = new Video("Revenge of the Ducks", "A. Duck", 9000);
In BlueJ
- Open CD class and set a breakpoint at first line of CD class constructor.
- Create a CD object.
- Inspect.
- Step Into to step through the execution.
- What constructor was executed for super()?
- Are Item fields part of the CD object in the Inspector?
| One | Two | Three |
|
|
|
Exercise 7.1 - Inheritance and initialization In your head
- For the Java code above, draw the UML class diagram similar to at right that shows inheritance of fields and methods.
- Trace the execution of:
- One myOne = new myOne("white");
- System.out.print( myOne.getOneS() );
- Trace the execution of:
- Two myTwo = new myTwo("red");
- System.out.print( myTwo.getTwoS() );
- Trace the execution of:
- Three myThree = new myThree("blue");
- System.out.print( myThree.getThreeS() );

| reuse - Using existing classes in a new context. |
Exercise 8 - Reuse In BlueJ
- Add the following constructor with no parameters to Item:
- public Item () { }
- Create a class Game that inherits from Item.
- Game class has no fields, constructors or methods.
- Create a class VideoGame that inherits from Game.
- VideoGame class has no fields, constructors or methods.
- Examine the class diagram.
- What class or classes are inherited by VideoGame?
|
Without Inheritance |
With Inheritance |
![]() |
|
| import java.util.ArrayList; import java.util.Iterator; public class Database { private ArrayList cds; private ArrayList videos; public Database() { cds = new ArrayList(); videos = new ArrayList(); }
public void list() |
import java.util.ArrayList; import java.util.Iterator; public class Database
|
Exercise 8.2 - Subtyping In BlueJ
- Open chapter08/dome-v2.
- Create Database, Video and CD objects.
- Add each Item to the database.
- List the database.

| Primitive type - Non-object types such as int, boolean, char, double. |
| Object type - Defined by classes. |
| Subtype - Defined by subclass hierarchy. |
The two following definitions are compatible.
| Variables and subtypes - Variables reference objects of their type or subtype. Cannot reference (i.e. be assigned) supertype objects. |
| Substitution - Subtype objects can be substituted wherever supertype object allowed. |
Item item1 = new Item();
Game game1 = new Game();
VideoGame vg1 = new VideoGame();

Compatible Types
Incompatible Types
item1 = game1;
game1 = vg1;Item item2 = new Game();
Game game2 = new VideoGame();game1 = item1;
vg1 = game1;
vg1 = item1;VideoGame vg2 = new Game();
Game game2 = new Item();

| Variables and subtypes - Variables reference objects of their type or subtype. Cannot reference (i.e. be assigned) supertype objects. |
| Substitution - Subtype objects can be substituted wherever supertype object allowed. |
Exercise 9 - Subtyping and assignments Which statements are true?
- Game is a subclass of Item.
- Game is a superclass of VideoGame.
- Game is a subclass of Video.
- Game is a superclass of Video.
Item item1 = new Item();
Game game1 = new Game();
VideoGame vg1 = new VideoGame();Which are valid (using above item1, game1 and vg1 definitions)?
- item1 = game1;
- game1 = item1;
- game1 = vg1;
- vg1 = item1;
- Item item2 = new Game();
- Game game2 = new Item();
- Video video1 = new Game();
| One | Two | Three |
|
|
|
Exercise 9.1 - Subtyping and assignments
- Give the inheritance hierarchy diagram for the above classes.
- Which are valid using the myOne, myTwo and myThree definitions?
One myOne;
Two myTwo;
Three myThree;
- myOne = myTwo;
- myOne = myThree;
- myThree = myTwo;
- myThree = myOne;
- myOne = new Two("purple");
- myTwo = new One("green");
- myThree = new Two("orange");
| Passing subtypes - Actual parameters can be passed to formal parameters of the same or supertype. |
| Passing supertypes - Actual parameters cannot be passed to formal parameters of a subtype. |

public class Database
{
public void addItem( Item theItem ) {}
public void addGame( Game theGame ) {}
public void addVideoGame( VideoGame theVidoGame ) {}
}Database db = new Database();
Item item1 = new Item();
Game game1 = new Game();
VideoGame vg1 = new VideoGame();
Compatible
Incompatible
db.addItem( item1 );
db.addItem( game1 );
db.addItem( vd1 );
db.addGame( vd1 );
db.addVideoGame( vd1 );db.addGame( item1 );
db.addVideoGame( item1 );
db.addVideoGame( game1 );
| Passing subtypes - Actual parameters can be passed to formal parameters of the same or supertype. |
| Passing supertypes - Actual parameters cannot be passed to formal parameters of a subtype. |
Exercise 10 - Parameter subtypes Which are valid (using above db, item1, game1 and vg1 definitions)?
- db.addItem(item1);
- db.addItem(game1);
- db.addItem(vg1);
Which are valid (using above db, item1, game1 and vg1 definitions)?
- db.addGame(item1);
- db.addGame(game1);
- db.addGame(vg1);
- db.addVideoGame(item1);
- db.addVideoGame(vg1);
- db.addVideoGame(game1);
| Polymorphic - Many shapes. |
Polymorphic method- When inherited methods are over-ridden, the type the object references determines the method executed.
| Variables and subtypes - Variables reference objects of their type or subtype. Cannot reference (i.e. be assigned) supertype objects. |
| Substitution - Subtype objects can be substituted wherever supertype object allowed. |
Classes can over-ride inherited methods (i.e. methods with the same name) and variables can reference objects of a subclass. For example, the following executes the getS() method of class Two at line 16:
Two aTwo = new Two("purple");
aTwo.getS();But the following executes the getS() method of class Three at line 29:
Two aTwo = new Three("purple");
aTwo.getS();The type the object referenced is Three so the Three method was executed.
| One | Two | Three |
|
|
|
Exercise 11a - Polymorphism
- Which are valid?
- Trace the execution.
- Note that One, Two and Three each have a getS() method.
One myOne = new One("red");
Two myTwo = new Two("white");
Three myThree = new Three("blue");
System.out.print( myOne.getS() );
System.out.print( myTwo.getS() );
System.out.print( myThree.getS() );
Exercise 11b - Polymorphism
- Which are valid?
- Trace the execution.
- Note that One, Two and Three each have a getS() method.
One myOne = new Two("red");
Two myTwo = new Three("white");
Three myThree = new One("blue");
System.out.print( myOne.getS() );
System.out.print( myTwo.getS() );
System.out.print( myThree.getS() );
|
Without inheritance |
With inheritance | ||
| public class Database {
|
public class Database {
|
Exercise 11.2 - Polymorphism Which are valid? Note that Item, CD and Video each have a print() method.
Item item1 = new Item();
Video video1 = new Video();
CD cd1 = new CD();video1.list();
cd1.list();
item1.list();
| Object - The top-level class. All classes inherit from Object class. |
| Variables and subtypes - Variables reference objects of their type or subtype. Cannot reference (i.e. be assigned) supertype objects. |
| Substitution - Subtype objects can be substituted wherever supertype object allowed. |
public class Item
public class Item extends Object
Exercise 12 - Object Are the following equivalent according to the hierarchy at right?
public class Game extends Object
public class Game extends ItemWhich are valid?
public class Database
{
public void addObject( Object theObject )
public void addItem( Item theItem )Database db = new Database();
Object object1 = new Object();
Item item1 = new Item();
- item1 = object1;
- object1 = item1;
- db.addObject( item1 );
- db.addObject( object1 );
- db.addItem( item1 );
- db.addItem( object1 );
Polymorphic collections can reference different types of objects. The Java collections ArrayList and
HashMap are examples, able to reference String, TicketMachine, Game or other objects.
This is possible because these collections are defined to reference Object types. From our rules repeated below, we know that a variable of type Object can reference an object any subtype.
ArrayList signatures are given below for the add() and get() methods. Because Object is the super-type of all types, an ArrayList element can reference any other type.
| Variables and subtypes - Variables reference objects of their type or subtype. Cannot reference (i.e. be assigned) supertype objects. |
| Substitution - Subtype objects can be substituted wherever supertype object allowed. |
| Passing subtypes - Actual parameters can be passed to formal parameters of the same or supertype. |
| Passing supertypes - Actual parameters can not be passed to formal parameters of a subtype. |
public class ArrayList
{
public void add( Object theObject )public Object get( int index)
public class HashMap
{
public void put( Object key, Object theObject )public Object get( Object key )
Now we can understand the need for casting.
The ArrayList method get() returns a reference to an Object. Object is the superclass so cannot be assigned to a subtypes such as Item, TicketMachine, etc. It must be cast to the correct type for the assignment.
Compile errors - The compiler can detect errors where a supertype is assigned to a subtype variable in // 1 below.
Runtime errors - The compiler can not detect errors where a subtype is assigned to the incorrect type
variable as in // 3 below. However, at runtime // 3 will cause the program to fail.
Why can't the compiler catch the error in // 3? Because at runtime the ArrayList element 1 could be a CD, Video or any other subtype of Object. It depends upon what we have added to the ArrayList.
ArrayList aL = new ArrayList();
aL.add( new CD() );
aL.add( new Video() );
CD cd1 = aL.get( 0 ); // 1. Compile error, CD = ObjectVideo vd1 = (Video) aL.get( 1 ); // 2. Compile OK
CD cd2 = (CD) aL.get( 1 ); // 3. Compile OK but runtime error!
CD = Video.
Exercise 12.1 - Polymorphism
- What is the hierarchy diagram classes One, Two and Three?
ArrayList aL = new ArrayList();
One aOne = new One("red");
Two aTwo = new Two("white");
Three aThree = new Three("blue");aL.add( aOne );
aL.add( aTwo );
aL.add( aThree );
- Diagram the ArrayList aL.
- Which of the following are valid syntax?
- aOne = aL.get(0);
- aOne = (One) aL.get(0);
- aThree = (One) aL.get(2);
- aThree = (Three) aL.get(2);
- aThree = (Two) aL.get(1);
- ((Three) aL.get(2)).getS();
- Which of the following give a runtime error?
- aOne = (One) aL.get(0);
- aThree = (Three) aL.get(2);
- aThree = (Three) aL.get(1);
- aTwo = (Two) aL.get(2);
- ((Three) aL.get(2)).getS();
| One | Two | Three |
|
|
|
| Wrapper classes - One common use is a class defined to encapsulate a primitive type for use as an object. |
You may have noticed that primitive types such as int, boolean, etc. are not used in collections such as ArrayList, HashMap, etc. The reason being that collections can only reference Objects.
Java already defines wrapper classes for all primitives. For example:
- Integer for int
- Double for double
The wrapper classes Integer and Double inherits from Object so that Integer or Double objects can be treated as normal objects while holding the value of the primitive type.
ArrayList aL = new ArrayList();
Integer integer1 = new Integer( 5 );
aL.add( integer1 );
aL.add( new Integer( 3 ) );
Integer integer2 = (Integer) aL.get( 0 );int int1 = integer2.intValue();
int int2 = ((Integer).get( 1 )).intValue();
Exercise 13 - Wrappers
- What is the value of int1 and int2?
Please send any comments to: jfdoyle@ius.edu
Copyright ©
2001-2004 by cgranda@ius.edu . All
rights reserved.