Chapter 8:


C201 Home Page


Chapter 8
Improving structure with inheritance

powered by FreeFind

Modified: 


 

 

 

Overview

Chapter 7 introduced the design of classes. Chapter 8 examines a fundamental object-oriented construct for reusing code: inheritance.

8 Introduction

  1.  public class TicketMachine
  2.  {
  3.     private int price;
  4.     private int balance;
  5.     private int total; 
     
  6.     public TicketMachine(int ticketCost)
  7.    {
  8.        price = ticketCost;
  9.        balance = 0;
  10.        total = 0;
  11.     }
     
  12.    public void insertMoney(int amount)
  13.    {
  14.        balance += amount;
  15.    }
     
  16.    public void printTicket()
  17.    {
  18.        System.out.println("# " + price +
                                      " cents.");
  19.        total += balance;
  20.        balance = 0;
  21.    }
  22. }
  1. public class BusTicketMachine extends TicketMachine
  2. {
  3.     private String bus, stops;
     
  4.     public BusTicketMachine( int theCost, String theBus,
                                           String theStops )
  5.     {
  6.           super( theCost );
  7.           bus = theBus;
  8.           stops = theStops;
  9.      }
     
  10.      public void printStops()
  11.      {
  12.          System.out.println("# Bus " + bus );
  13.          System.out.println("# Stops " + stops );
  14.      } 
     
  15.      public void printTicket()
  16.      {
  17.          System.out.println("# Ticket for bus  " + bus );
  18.          super.printTicket();
  19.      } 
  20. }
              
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( );

8.1 The DoME example

Database of CD's and video's.

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?

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.

 

 

8.1.2 DoME source code

Exercise 3 - Need for Inheritance
  1. How are CD and Video methods the same?
     
  2. How are CD and Video fields the same?
     
  3. How are the CD and Video methods different?
     
  4. 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

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
      }
   }
}
Exercise 3.5 - Need for Inheritance
  1. What fields are similar?
     
  2. What methods are similar

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

  1. Open project chapter08/dome-v1
  2. Create one CD and Video objects.
  3. Create one Database object.
  4. Enter the CD and Video objects into the Database object.
  5. List the database contents.
    • Do any objects have comments?
  6. Add a comment to one of the Video objects.
  7. List the database contents.
    • Can you explain the printed output by the figure at right and examining CD and Video print() methods below?
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);
   }
}

8.2 Using inheritance

 

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()
   {
      System.out.print("title: " + title + " (" + playingTime + " mins)");
      if(gotIt) {
         System.out.println("*");
      } else {
         System.out.println();
      }
      System.out.println(" " + comment);
   }
}

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()
   {
      System.out.println(" " + director);
   }

}

8.3 Inheritance hierarchies

Exercise 5 - Inheritance hierarchies
  1. Extend the hierarchy diagram at right to include jazz, blues, R&R, country western and rap.
  2. Extend the hierarchy diagram at right to include musicals, science fiction, soap operas, TV shows and comedy.

8.4 Inheritance in Java

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 setComment(String comment)

 public String getComment()

 public void setOwn(boolean ownIt)
 
 public boolean getOwn()

 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;   }
}

8.4.1 Inheritance and access rights

Exercise 6 - Inheritance and access rights

In BlueJ

  1. Open project Chapter08/dome-v2
  2. Create a CD object.
    • Call a public inherited method such as setComment().
  3. Open class Video
  4. Remove the extends Item
    • What is the result of compiling Video?
    • Why?
  5. Restore the extends Item

8.4.2 Inheritance and initialization

Item Video CD
  1. public class Item
  2. {
  3.    private String title;
  4.    private int playingTime;
  5.    private boolean gotIt;
  6.    private String comment;
     
  7.    public Item(String theTitle,
                             int time)
  8.    {
  9.       title = theTitle;
  10.       playingTime = time;
  11.       gotIt = false;
  12.       comment = "";
  13.    }
  1. public class Video extends Item
  2. {  
  3.     private String director;
     
  4.     public Video(String theTitle,
                          String theDirector,
                          int time)

  5.    {

  6.       super(theTitle, time);

  7.       director = theDirector;

  8.    }
     

  1. public class CD extends Item
  2. {
  3.    private String artist;
  4.    private int numberOfTracks;
     
  5.    public CD(String theTitle,
                      String theArtist,
                      int tracks,
                      int time)

  6.    {

  7.       super(theTitle, time);

  8.       artist = theArtist;

  9.       numberOfTracks = tracks;

  10.    }
     

Exercise 7 - Inheritance and initialization

In your head

  1. Trace the execution of:
    • CD mycd = new CD("Quacker", "Duck", 300, 10000);
  2. Trace the execution of:
    • Video myvideo = new Video("Revenge of the Ducks", "A. Duck", 9000);

In BlueJ

  1. Open CD class and set a breakpoint at first line of CD class constructor.
  2. 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
  1. public class One
  2. {
  3.    private String oneS;
     
  4.    public One(String theS)
  5.    {
  6.       oneS = theS;
  7.    }
     
  8.    public String getOneS()
  9.    {
  10.        return oneS;
  11.    }
  12. }
  1. public class Two extends One
  2. {  
  3.     private String twoS;
     
  4.     public Two(String theS)

  5.    {

  6.       super("red");

  7.       twoS = theS;

  8.    }
     

  9.    public String getTwoS()
  10.    {
  11.        return twoS;
  12.    }
  13. }
  1. public class Three extends Two
  2. {
  3.    private String threeS;
     
  4.    public Three(String theS)

  5.    {

  6.       super("blue");

  7.       threeS = theS;

  8.    }
     

  9.    public String getThreeS()
  10.    {
  11.        return threeS;
  12.    }
  13. }
Exercise 7.1 - Inheritance and initialization

In your head

  1. For the Java code above, draw the UML class diagram similar to at right that shows inheritance of fields and methods.
     
  2. Trace the execution of:
    • One myOne = new myOne("white");
    • System.out.print( myOne.getOneS() );
       
  3. Trace the execution of:
    • Two myTwo = new myTwo("red");
    • System.out.print( myTwo.getTwoS() );
       
  4. Trace the execution of:
    • Three myThree = new myThree("blue");
    • System.out.print( myThree.getThreeS() );

8.5 DoME: adding other item types

Exercise 8 - Reuse

In BlueJ

  1. Add the following constructor with no parameters to Item:
    • public Item () { }
  2. Create a class Game that inherits from Item.
    • Game class has no fields, constructors or methods.
  3. Create a class VideoGame that inherits from Game.
    • VideoGame class has no fields, constructors or methods.
  4. Examine the class diagram.
    • What class or classes are inherited by VideoGame?

8.6 Advantages of inheritance (so far)

8.7 Subtyping

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 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
      }
   }
}

import java.util.ArrayList;
import java.util.Iterator;

public class Database
{
   private ArrayList items;


   public Database()
   {
      items = new ArrayList();
   }

   public void addItem(Item theItem)
   {      items.add(theItem);     }





   public void list()
   {
      for(Iterator iter = items.iterator(); iter.hasNext(); )
      {
         Item item = (Item) iter.next();
         item.print();
      }
   }
}
 

Exercise 8.2 - Subtyping

In BlueJ

  1. Open chapter08/dome-v2.
  2. Create Database, Video and CD objects.
  3. Add each Item to the database.
  4. List the database.

8.7.1 Subclasses and subtypes

8.7.2 Subtyping and assignment

The two following definitions are compatible.

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();

Exercise 9 - Subtyping and assignments

Which statements are true?

  1. Game is a subclass of Item.
  2. Game is a superclass of VideoGame.
  3. Game is a subclass of Video.
  4. 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)?

  1. item1 = game1;
  2. game1 = item1;
  3. game1 = vg1;
  4. vg1 = item1;
  5. Item item2 = new Game();
  6. Game game2 = new Item();
  7. Video video1 = new Game();
One Two Three
  1. public class One
  2. {
  3.    private String oneS;
     
  4.    public One(String theS)
  5.    {
  6.       oneS = theS;
  7.    }
  1. public class Two extends One
  2. {  
  3.     private String twoS;
     
  4.     public Two(String theS)

  5.    {

  6.       super("red");

  7.       twoS = theS;

  8.    }

  1. public class Three extends Two
  2. {
  3.    private String threeS;
     
  4.    public Three(String theS)

  5.    {

  6.       super("blue");

  7.       threeS = theS;

  8.    }

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;

  1. myOne = myTwo;
  2. myOne = myThree;
  3. myThree = myTwo;
  4. myThree = myOne;
  5. myOne = new Two("purple");
  6. myTwo = new One("green");
  7. myThree = new Two("orange");

8.7.3 Subtyping and parameter passing

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 );
Exercise 10 - Parameter subtypes

Which are valid (using above db, item1, game1 and vg1 definitions)?

  1. db.addItem(item1);
  2. db.addItem(game1);
  3. db.addItem(vg1);

Which are valid (using above db, item1, game1 and vg1 definitions)?

  1. db.addGame(item1);
  2. db.addGame(game1);
  3. db.addGame(vg1);
  4. db.addVideoGame(item1);
  5. db.addVideoGame(vg1);
  6. db.addVideoGame(game1);

8.7.4 Polymorphic variables

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
  1. public class One
  2. {
  3.    private String oneS;
     
  4.    public One(String theS)
  5.    {
  6.       oneS = theS;
  7.    }
     
  8.    public String getS()
  9.    {
  10.        return oneS;
  11.    }
  12. }
  1. public class Two extends One
  2. {  
  3.     private String twoS;
     
  4.     public Two(String theS)

  5.    {

  6.       super("red");

  7.       twoS = theS;

  8.    }
     

  9.    public String getS()
  10.    {
  11.        return twoS;
  12.    }
  13. }
  1. public class Three extends Two
  2. {
  3.    private String threeS;
     
  4.    public Three(String theS)

  5.    {

  6.       super("blue");

  7.       threeS = theS;

  8.    }
     

  9.    public String getS()
  10.    {
  11.        return threeS;
  12.    }
  13. }
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 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
      }
   }
 
public class Database
{
   public void list()
   {
      for(Iterator iter = items.iterator(); iter.hasNext(); )
      {
         Item item = (Item) iter.next();
         item.print();
      }
   }

 

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();

8.8 The Object class

 

Exercise 12 - Object

Are the following equivalent according to the hierarchy at right?

  public class Game extends Object
  public class Game extends Item

Which 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();

  1. item1 = object1;
  2. object1 = item1;
  3. db.addObject( item1 );
  4. db.addObject( object1 );
  5. db.addItem( item1 );
  6. db.addItem( object1 );

8.9 Polymorphic collections

8.9.1 Element types

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.

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 )

8.9.2 Casting revisited

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 = Object

Video 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?
     
    1. aOne = aL.get(0);
    2. aOne = (One) aL.get(0);
    3. aThree = (One) aL.get(2);
    4. aThree = (Three) aL.get(2);
    5. aThree = (Two) aL.get(1);
    6. ((Three) aL.get(2)).getS();
       
  • Which of the following give a runtime error?
     
    1. aOne = (One) aL.get(0);
    2. aThree = (Three) aL.get(2);
    3. aThree = (Three) aL.get(1);
    4. aTwo = (Two) aL.get(2);
    5. ((Three) aL.get(2)).getS();
One Two Three
  1. public class One
  2. {
  3.    private String oneS;
     
  4.    public One(String theS)
  5.    {
  6.       oneS = theS;
  7.    }
     
  8.    public String getS()
  9.    {
  10.        return oneS;
  11.    }
  12. }
  1. public class Two extends One
  2. {  
  3.     private String twoS;
     
  4.     public Two(String theS)

  5.    {

  6.       super("red");

  7.       twoS = theS;

  8.    }
     

  9.    public String getS()
  10.    {
  11.        return twoS;
  12.    }
  13. }
  1. public class Three extends One
  2. {
  3.    private String threeS;
     
  4.    public Three(String theS)

  5.    {

  6.       super("blue");

  7.       threeS = theS;

  8.    }
     

  9.    public String getS()
  10.    {
  11.        return threeS;
  12.    }
  13. }

8.9.3 Wrapper classes

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:

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?

8.10 The collection hierarchy

8.11 Summary



C201 Home Page


Please send any comments to: jfdoyle@ius.edu 
Copyright © 2001-2004 by cgranda@ius.edu . All rights reserved.