java programming: from the ground up chapter 12: inheritance

113
Java Programming: From the Ground Up Chapter 12: Inheritance

Upload: shonda-wilkerson

Post on 18-Jan-2016

232 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Programming: From the Ground Up Chapter 12: Inheritance

Java Programming:From the Ground Up

Chapter 12:Inheritance

Page 2: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance

• Inheritance makes it possible to build new classes from existing classes thus facilitating the reuse of methods and data from one class in another.

• Inheritance allows data of one type to be treated as data of a more general type.

Page 3: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

• A basic remote control unit that can be used to turn a TV on or off, raise and lower the volume, or change the channel.

• Volume levels range from 0 to 20 and channel numbers from 1 to 199.

• Pressing a volume (channel) button, increases or decreases the volume (channel) by one unit.

• For example, if the current channel is 5, pressing the “channel up” button twice sets the channel to 7.

Page 4: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

Problem Statement:

• Implement a Remote class that models the remote control unit.

• When the TV is initially switched on, the default channel is 2 and the default volume is 5.

Page 5: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

Java Solution:

• The Remote class has two attributes:

– volume, an integer in the range 0 through 20, and – channel, an integer in the range 1 through 199.

• The methods simulate the functions of the buttons. These methods are:

– channelUp() and channelDown(), which respectively increase and decrease channel by one, and

– volumeUp() and volumeDown(), which increase or decrease volume.

• The Remote class implements two additional methods:

– display(), which displays the current volume and channel, and – menu(), which presents a list of options to a user.

• Each time a user “presses any button,” display() shows the current channel and the volume.

Page 6: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

1. import java.util.*;2. public class Remote3.  4. {5. protected int volume; // notice the protected access modifier6. protected int channel;

7. protected final int MAXIMUM_VOLUME = 20; // highest volume setting8. protected final int MAXIMUM_CHANNEL = 199; // highest channel number9. protected final int DEFAULT_CHANNEL = 2; // default channel number10. protected final int DEFAULT_VOLUME = 5; // default volume setting11. protected final int MINIMUM_VOLUME = 0; // minimum volume, no sound12. protected final int MINIMUM_CHANNEL = 1; // lowest channel number

13. public Remote() // default constructor14. {15. channel = DEFAULT_CHANNEL; 16. volume = DEFAULT_VOLUME;17. }

Page 7: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

18. public Remote(int ch, int vol ) // two argument constructor19. // assumes valid data20. {21. channel = ch; 22. volume = vol;23. }

24. public void volumeUp() // increase volume by one unit25. {26. if (volume < MAXIMUM_VOLUME) // cannot exceed MAXIMUM_VOLUME27. volume++;28. }29.  30. public void volumeDown() // decrease volume by one unit31. {32. if (volume >MINIMUM_VOLUME) // not lower than MINIMUM_VOLUME33. volume--;34. }

Page 8: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

35. public void channelUp() // increase channel number by 136. {37. if (channel < MAXIMUM_CHANNEL ) // cannot exceed MAXIMUM_CHANNEL 38. channel++;39. }40. public void channelDown() // decrease channel number by 141. {42. if (channel > MINIMUM_CHANNEL) // not lower than MINIMUM_CHANNEL43. channel--;44. }45.  46. public void display() // show the volume and the channel47. {48. System.out.println("\n----------------------");49. System.out.println("Channel: "+ channel);50. System.out.println("Volume: "+ volume);51. System.out.println("----------------------\n");52. }

Page 9: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

53. public void menu() // presents user with the choices of Figure 12.254. {55. Scanner input = new Scanner(System.in);56. String choice;57. System.out.println("POWER ON");58. display();59. do60. {61. System.out.println("Channel up: +");62. System.out.println("Channel down: -");63. System.out.println("Volume up: ++");64. System.out.println("Volume down: --");65. System.out.println("Power off: o");66. System.out.print("Choose: ");67. choice = input.next();

Page 10: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

68. if (choice.equals("+"))69. channelUp();70. else if (choice.equals("-"))71. channelDown();72. else if (choice.equals("++"))73. volumeUp();74. else if (choice.equals("--"))75. volumeDown();76. display();77. } while (! choice.equals("o"));78. System.out.println("POWER OFF");79. }80.  81. public static void main(String[] args)82. {83. Remote remote = new Remote();84. remote.menu();85. }86. }

Page 11: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

• Through inheritance, extend the Remote class so that the attributes and methods of Remote can be used (or reused) to build a new class with all of the features of Remote and then some.

• Inheritance is the mechanism that allows us to reuse the attributes and methods of one class in the implementation of another class.

Page 12: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

Example: an upgraded version of the no frills remote.

• The last button on the new remote switches the channel back to the previously viewed channel.

• The direct access remote is a no frills remote with additional functionality.

Page 13: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

Problem Statement:

• Implement a class, DirectRemote

Page 14: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

Java Solution:

• DirectRemote is not much different than Remote.

• The attributes and methods of Remote, such as volumeUp() and volumeDown(), can be used (or reused) in the implementation of DirectRemote.

• DirectRemote need not be built “from scratch.”

• Remote can give its attributes and methods to DirectRemote, or stated differently, DirectRemote can inherit the attributes and methods of Remote.

Page 15: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

• The clause extends Remote in the class heading

– public class DirectRemote extends Remote (line 2 below)

declares that DirectRemote inherits from Remote.

• That is, DirectRemote has the features and functionality of Remote and possibly more.

Page 16: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

• The following implementation of DirectRemote does not explicitly declare the instance variables channel and volume; they are inherited from Remote.

• DirectRemote does not implement volumeUp() or display(); they come to DirectRemote via inheritance.

• DirectRemote has the option of declaring its own additional variables and providing its own implementation of any method, new or inherited.

• In particular, DirectRemote implements new methods that handle direct channel access and last channel access, and provides its own modified versions of channelUp() and channelDown().

Page 17: Java Programming: From the Ground Up Chapter 12: Inheritance

A Basic Remote Control Unit

• Each variable, constant, and method is present and available because DirectRemote inherits it from Remote.

• Remote is called a base class, a superclass, or a parent class and DirectRemote a derived class, a subclass, or a child class.

• Besides the new keyword, extends, the following implementation of DirectRemote includes two additional new keywords: protected and super.

Page 18: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

1. import java.util.*;2. public class DirectRemote extends Remote //Remote is the base class; DirectRemote a

subclass3. {4. protected int lastChannel; // to reset to the previous channel

5. public DirectRemote() // default constructor6. {7. super(); // call the default constructor of remote8. lastChannel = DEFAULT_CHANNEL; //DEFAULT_CHANNEL inherited from Remote9. }

10. public DirectRemote(int ch, int vol, int last) // three-argument constructor11. {12. super(ch, vol); // a call to the two-argument constructor of Remote13. lastChannel = last;14. }

Page 19: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

15. public void channelUp() // overrides the channelUp() method of Remote16. {17. lastChannel = channel;18. super.channelUp(); // a call to the channelUp() method of Remote19. }

 20. public void channelDown() // overrides the channelDown() method of Remote21. {22. lastChannel = channel;23. super.channelDown(); // a call to the channelDown() method of Remote24. } 25. public void setChannel(int ch) 26. {27. lastChannel = channel;28. channel = ch;29. }

Page 20: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

30. public void last() // sets channel to previously viewed channel31. {32. int temp = channel;33. channel = lastChannel;34. lastChannel = temp;35. }

36. public void menu() // the user interface37. {38. Scanner input = new Scanner(System.in);39. String choice;40. System.out.println("POWER ON");41. display(); //method inherited from Remote42. do43. {44. System.out.println("Channel up: +");45. System.out.println("Channel down: -");46. System.out.println("Wolume up: ++");47. System.out.println("Volume down: --");48. System.out.println("Last channel: <<");49. System.out.println("Enter channel number: ");50. System.out.println("Power off o");51. System.out.print("Choose: ");

Page 21: Java Programming: From the Ground Up Chapter 12: Inheritance

52. choice = input.next();53. if (choice.equals("+"))54. channelUp(); // overrides the Remote methode55. else if (choice.equals("-"))56. channelDown(); // overrides the Remote method57. else if (choice.equals("++"))58. volumeUp(); // inherited from Remote59. else if (choice.equals("--"))60. volumeDown(); // inherited from Remote61. else if (choice.equals("<<"))62. last(); // resets channel to previously viewed

channel63. else if ( !choice.equals("o")) // choice is a number or invalid64. {65. int ch = getChannel(choice);66. if (ch >=1 && ch <= 200) // if valid channel67. setChannel(ch);68. }69. display();70. } while (! choice.equals("o"));71. System.out.println("POWER OFF");72. }

Page 22: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

73. private int getChannel(String ch) // a helper method74. // converts a string of digits to an integer75. // if a character of ch is not a digit returns 076. {77. int number = 0;78. for (int i = 0; i <ch.length(); i++)79. {80. char digit = ch.charAt(i);81. if ( digit > '9' || digit < '0')82. return 0;83. number = 10*number + (digit - '0');84. }85. return number;86. }

Page 23: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

87. public static void main(String[] args)88. {89. DirectRemote remote = new DirectRemote();90. remote.menu();91. }92. }

Page 24: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

Discussion

• The keyword protected:

– The access modifier protected falls between public and private.

– A private variable or method is visible only to its defining class.

– A public variable or method is visible to any class. – A protected variable or method is visible to its defining

class and all its subclasses, as well as any other classes in the same package.

Page 25: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

• Because the instance variables, channel and volume, of the base class Remote are protected, they are visible to the derived class DirectRemote.

• DirectRemote inherits these attributes from parent Remote and has access to channel and volume.

• If volume and channel were declared private in Remote, they would not be visible to DirectRemote, and DirectRemote would not be able to alter these variables except via getter and setter methods.

• The public methods of Remote are also inherited by DirectRemote.

• Both Remote and DirectRemote implement channelUp(), channelDown(), and menu().

• DirectRemote overrides Remote’s version of these methods.

• That is, DirectRemote has its own versions of these methods that are different from Remote’s version.

Page 26: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

• A subclass inherits all public and protected methods of a base class unless the subclass overrides a method thus providing its own implementation.

• There is one notable exception to the inheritance rule for methods.

• A subclass does not inherit the constructors of the base class.

• The constructors of a base class are not considered constructors of a subclass.

Page 27: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

Line 2: DirectRemote extends Remote

• The phrase DirectRemote extends Remote indicates that Remote is the base class and DirectRemote a child class.

• DirectRemote inherits from Remote.

Line 4: protected int lastChannel;

• DirectRemote declares an additional instance variable, lastChannel with protected access.

• Thus, any class that extends DirectRemote inherits lastChannel.

• The variable lastChannel is declared in DirectRemote and is not an attribute of Remote, the parent class.

• A Remote object knows nothing of lastChannel.

Page 28: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

Lines 5-14:

• The statements contained on lines 5-14 define a default constructor and a three argument constructor for DirectRemote.

• As mentioned above, a child class does not inherit the constructors of the parent.

• However a child class may invoke a parent constructor using the keyword super as shown on lines 7 and 12:

– super() calls the default constructor of Remote (line 7), and – super(ch, vol) calls the two-argument constructor of Remote (line 12).

• If super is used, then it must be the first statement of a constructor.

• Finally, we note that if a base class constructor is not explicitly called using super, the default constructor of the base class is automatically invoked.

• In this case, if the default constructor of the base class does not exist, a compilation error results.

Page 29: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

Lines 15-19:

15. public void channelUp() // overrides the channelUp() method of Remote16. {17. lastChannel = channel;18. super.channelUp(); // a call to the channelUp() method of Remote19. }

• Because lastChannel (defined in DirectRemote) must be reset each time the channel is changed, the channelUp() method inherited from Remote is not suitable.

• A new channelUp() method overrides the channelUp() method of Remote.

• This version of channelUp() first stores the value of the current channel (channel) in the instance variable lastChannel, and then invokes the channelUp() method of the base class with the keyword super:

super.channelUp(),

which increments channel, provided channel is currently less than MAX_CHANNEL.

Page 30: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

Lines 20-24:

20. public void channelDown() // overrides the channelDown() method of Remote21. {22. lastChannel = channel;23. super.channelDown(); // a call to the channelDown() method of Remote24. } 

• As with channelUp(), this method overrides the corresponding channelDown() method of Remote.

• Notice the call to channelDown() of the parent class: super.channelDown().

Page 31: Java Programming: From the Ground Up Chapter 12: Inheritance

Lines 25-29:

• public void setChannel(int ch) • {• lastChannel = channel;• channel = ch;• }

These lines define a setter method that sets channel.

Lines 30-35:

30. public void last() // sets channel to previously viewed channel31. {32. int temp = channel;33. channel = lastChannel;34. lastChannel = temp;35. }

The last() method swaps channel with lastChannel making the current channel the previously viewed channel.

Page 32: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

Lines 36-72:

• The menu() method presents the user with a menu of options that correspond to the buttons on the remote unit .

• When the user makes a choice, the corresponding button is “pressed.”

• After every choice, display() shows the current values of the instance variables channel and volume.

• DirectRemote inherits display() from Remote.

Page 33: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

Lines 73-86:

• The method:

int getChannel(String ch)

is a helper method with private access.

• Thus, the method is not accessible outside of the class.

• This method accepts a string version of channel number and returns the channel number as an integer.

• If the string ch contains characters that do not represent digits, the method returns the invalid channel, 0.

Page 34: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

DirectRemote extends Remote

Page 35: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

• The keyword extends signifies an inheritance relationship.

• DirectRemote extends Remote means that DirectRemote inherits from Remote and that Remote is a parent class of DirectRemote.

• The Remote class is called the base class, superclass, or parent class, and DirectRemote is the derived class, subclass or child class.

• The access modifier protected is used in a base class.

• A protected variable or method is visible to any subclass or any class in the same package.

Page 36: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

• A derived class inherits the data and methods of the base class that are not private.

• Additionally, a derived class can override or redefine an inherited base class method.

• For example, DirectRemote can override a Remote method and provide its own implementation.

• In particular, DirectRemote overrides menu(), channelUp(), and channelDown(), which are defined in Remote.

• Note, however, that a subclass may not override a public method with a private access modifier.

• In general, you may not assign more restrictive access privileges to an overridden method.

• A derived class can include new methods and variables that are not part of the base class.

Page 37: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

• DirectRemote defines the instance variable lastChannel and the method setChannel(), which are not inherited from Remote. lastChannel has protected access.

• Any class that extends DirectRemote inherits lastChannel.

• Constructors are not inherited.

• The constructors of a derived class can invoke the constructors of the parent class with the keyword super, i.e., super() or super(…).

• If a derived class calls a base class constructor with the keyword super, the call must occur before any other code is executed in the base class constructor.

Page 38: Java Programming: From the Ground Up Chapter 12: Inheritance

DirectRemote, a subclass of Remote

• If a derived class does not make an explicit super(…) call to a base class constructor, the default constructor of the base class is automatically invoked.

• If the base class defines constructors but not a default constructor and the derived class does not make an explicit super(…) call, a compilation error occurs.

• The derived class cannot rely on the automatic invocation of the default constructor, because the default constructor of the parent does not exist.

• If a derived class overrides a method x(), the base class version of x() is still available to the derived class and can be invoked using the keyword super:

super.x().

Page 39: Java Programming: From the Ground Up Chapter 12: Inheritance

The is-a Relationship: A DirectRemote is-a Remote

• Inheritance allows the creation of a more specialized class from a base class.

• A derived class extends the attributes and/or functionality of the base class.

• A derived class has everything that the base class has, and more

• Constructors are not inherited.

• Inheritance enables code reuse.

• The relationship between the base class and a derived class is termed an is-a relationship because every derived class is-a (kind of) superclass.

Page 40: Java Programming: From the Ground Up Chapter 12: Inheritance

The is-a Relationship: A DirectRemote is-a Remote

• A DirectRemote is-a Remote in the sense that a DirectRemote object can do everything that a Remote object can do.

• A DirectRemote object has all the attributes and functionality of a Remote object, and more.

• When deciding whether or not to extend a class, you should determine whether or not an is-a relationship exists.

• If not, inheritance is probably inappropriate.

Page 41: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

A Film class has attributes:

– title,– director, – screenwriter, and – total box office gross, in millions of dollars adjusted for

inflation.

The methods of a Film class include:

– constructors, – getters and setters, and – a method that displays the values of each attribute.

Page 42: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

Like a Film object, a Play object has:

– a title, – a director, and – a writer or playwright.

• Additionally, a Play object also holds the number of performances of a play.

• The Play methods are:

– getter and setter methods, and – a method that displays the values of each attribute.

Page 43: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

A Play class and a Film class

Page 44: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

• The Play class and the Film class are very similar and share many of the same attributes and methods.

• Should one class extend the other?

• On one hand, a Play is not a Film and a Film is not a Play.

• On the other hand, Play and Film share many of the same attributes.

• Couldn’t these attributes and methods be passed from one class to the other?

Page 45: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

• To exploit code reuse, we factor out what is common to Film and Play and design a new class, Production, so that Production has all the attributes and methods common to both Film and Play.

• Moreover, a Film is-a Production and similarly a Play is-a Production. Production is a base class designed for inheritance and not instantiation. Film extends Production, and Play extends Production.

• The raison d’etre for Production is inheritance, not instantiation.

Page 46: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

Play extends Production; Film extends Production

Page 47: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

Problem Statement:

• Implement Production as well as subclasses Play and Film

Page 48: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

Java Solution Production defines the attributes and methods common to Film and Play.

1. public class Production2. {3. protected String title;4. protected String director;5. protected String writer;6. public Production() // default constructor7. {8. title= "";9. director = "";10. writer = "";11. }

12. public Production(String t, String d, String w) // three argument constructor13. {14. title= t;15. director = d;16. writer = w;17. }

Page 49: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

18. public String getTitle()19. {20. return title;21. }

22. public String getDirector()23. {24. return director;25. }

26. public String getWriter()27. {28. return writer;29. }

30. public void setTitle(String t)31. {32. title = t;33. }

Page 50: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

34.public void setDirector(String d)35. {36. director = d;37. }

38. public void setWriter(String w)39. {40. writer = w;41. }

42. public void display()43. {44. System.out.println("Production class");45. }46. }

Page 51: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

47. public class Play extends Production48. {49. protected int performances;50. public Play()51. {52. super(); // call Production default constructor53. performances = 0;54. }

 55. public Play(String t, String d, String w, int p)56. {57. super(t,d,w); // call Production constructor58. performances = p;59. }

 60. public int getPerformances()61. {62. return performances;63. }

Page 52: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

64. public void setPerformances(int p)65. {66. performances = p;67. }

68. public void display()69. {70. System.out.println("Title: "+ title);71. System.out.println("Director: "+ director);72. System.out.println("Playwright: "+ writer);73. System.out.println("Performances: " + performances);74. }75. }

Page 53: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

76. public class Film extends Production77. {78. protected int boxOfficeGross;79. public Film()80. {81. super(); // call Production default constructor82. boxOfficeGross = 0;83. } 

84. public Film(String t, String d, String w, int g)85. {86. super(t,d,w); // call Production constructor87. boxOfficeGross = g;88. }

89. public int getBoxOfficeGross()90. {91. return boxOfficeGross;92. }

Page 54: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

93. public void setBoxOfficeGross(int g)94. {95. boxOfficeGross = g;96. }

97. public void display ()98. {99. System.out.println("Title: "+ title);100. System.out.println("Director: "+ director);101. System.out.println("Screenwriter: "+ writer);102. System.out.println("Total gross: $"+ boxOfficeGross+" million");103. }104. }

Page 55: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Factoring

Discussion:

• Subclasses Film and Play inherit the data and methods of the base class Production.

• Film is-a Production and Play is-a Production.

• Both Play and Film extend Production.

• Each overrides display() and each has an additional instance variable.

• Because Production is designed for inheritance and not for implementation, the display() method of Production does no more than print the name of the class, “Production.”

• The method is not strictly necessary; it is there to be overridden.

Page 56: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

• The Production class is a base class designed for inheritance and not instantiation.

• A Film is-a Production and a Play is-a Production.

• A Production is abstract, a Play or Film is concrete.

• Java’s notion of an abstract class is very precise:

– An abstract class is a class that cannot be instantiated.

– However, an abstract class can be inherited.

Page 57: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

• In general, an abstract class has the following properties:

• The keyword abstract denotes an abstract class. For example,

public abstract class Production

specifies that Production is an abstract class.

• An abstract class cannot be instantiated. You cannot create an object of an abstract class.

• An abstract class can be inherited by other classes. An abstract class is designed for inheritance not instantiation.

• An abstract class may contain abstract methods.

Page 58: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

• An abstract method is a method with no implementation. For example, the method

public abstract void display(); // method has no body

is an abstract method. Notice the keyword abstract and the terminal semicolon.

 • If an abstract class contains abstract methods, those methods

must be overridden in any non-abstract subclass; otherwise the subclass is also abstract.

• All abstract classes and methods are public. • To be of any use, an abstract class must be extended.

Page 59: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

• The Production class is an excellent candidate for an abstract class.

• Production is designed for inheritance and not instantiation.

• As an abstract class, Production has the following form:

public abstract class Production{ // all attributes and methods, except display(), are as

before public abstract void display(); // Look! No

implementation}

Page 60: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

• The keyword abstract in the heading indicates that Production cannot be instantiated; Production is designed solely as a base class.

• Also, display() is tagged an abstract method: display() has no implementation.

• Every non-abstract or concrete subclass that extends Production must implement the abstract method display().

• Thus, any non-abstract subclass of Production is guaranteed to have a display() method.

• A subclass that does not implement every abstract method of its parent class is also abstract and cannot be instantiated.

Page 61: Java Programming: From the Ground Up Chapter 12: Inheritance

Extending the Hierarchy

• A Musical is-a Play with songs.

• A Musical object has all the attributes of a Play object as well as a composer and a lyricist.

Page 62: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

Problem Statement

• Implement Musical as a subclass of Play.

• Include new attributes:

– String composer, and– String lyricist

along with getter and setter methods.

• Override display() to include all attributes of a Musical object.

Page 63: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

Java Solution Musical inherits the attributes and methods of Play and adds just a few of its own.

• class Musical extends Play• {• protected String composer;• protected String lyricist;• public Musical() // default constructor• {• super(); // invokes the default constructor of Play• composer = "";• lyricist = "";• }• public Musical(String t, String d, String w, String c, String l, int p)• // t(itle), d(irector), w(riter), c(omposer), l(yricist), p(erformances)• {• super(t,d,w,p); // invokes the 4-argument constructor of Play• composer = c;• lyricist = l;• }

Page 64: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

18. public String getComposer()19. {20. return composer;21. }

22. public void setComposer(String c)23. {24. composer = c;25. }

26. public String getLyricist()27. {28. return lyricist;29. }

30. public void setLyricist(String l)31. {32. lyricist = l;33. }

Page 65: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

34. public void display() // overrides the display() method of Play

35. {36. System.out.println("Title: "+ title);37. System.out.println("Director: "+ director);38. System.out.println("Playwright: "+ writer);39. System.out.println("Composer: "+ composer);40. System.out.println("Lyricist: "+ lyricist);41. System.out.println("Performances: " + performances);42. }43. }

Page 66: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheritance via Abstract Classes

The Production hierarchy

Page 67: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

• A Musical is-a Play and, as such, Java considers a Musical object a Play object.

Play play = new Musical("Sweeny Todd", "Harold Prince","Hugh Wheeler", "Stephen Sondheim", " Stephen Sondheim", 557);

Or

Play play;Musical musical = new Musical("South Pacific", "Joshua Logan","Oscar

Hammerstein“, "Richard Rodgers", " Oscar Hammerstein", 1925);

play = musical;

Page 68: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

• Play reference refers to a Musical object.

• This type of assignment is called upcasting.

• Upcasting is a language feature that allows a base-type reference to refer to an object of a derived type.

• Thus any object of a class derived from Play (e.g., Musical) is also considered a Play object.

• Objects of a derived type may be considered objects of the base type.

Page 69: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

• Even though Production is an abstract class that cannot be instantiated, any type derived from Production may be upcast to Production.

– Production p = new Film(), – Production q = new Play(), and– Production r = new Musical()

are all valid assignments.

• Production s = new Production() is not valid.

Page 70: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

• The statements:

– Play play= new Play();– Musical musical = play;– generate a compiler error.

• The reference musical refers to a Musical object and a Play object does not qualify as a Musical object.

• Every Play is not a Musical.

• However, under certain conditions, an explicit downcast is permissible.

Page 71: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting• Downcasting means casting an object to a derived or more specialized

type.

1. Play play = new Musical();2. Musical musical = (Musical)play;3. musical.getComposer();

 Line 1:

– The variable play is a Play reference. A Musical is-a Play. There is no problem here; the assignment is legal. This is an example of upcasting.

Page 72: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

1. Play play = new Musical();2. Musical musical = (Musical)play;3. musical.getComposer();

Line 2:

• The variable musical is a Musical reference.

• The reference play is a Play reference which, in this case, refers to a Musical object.

• The assignment is legal with an explicit downcast.

• As a Play reference, play is unaware of its status as a Musical unless explicitly downcast to Musical.

• The statement :

• Musical musical = play;

without the explicit downcast, generates an error.

• The downcast informs the compiler that play actually refers to a Musical object.

Page 73: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

1. Play play = new Musical();2. Musical musical = (Musical)play;3. musical.getComposer();

Line 3:

• The variable musical is a Musical reference and getComposer() is a Musical method.

Page 74: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

• The next lines do not compile:

Play play = new Musical(…);String name = play.getComposer() ;

• Line 1 is a valid upcast.

• The compiler complains about the method call on line 2.

• To the compiler, play is a Play reference and Play has no getComposer() method.

• Because a Musical object is instantiated (line 1), an explicit downcast informs the compiler that play refers to a Musical object and fixes the problem:

Play play = new Musical(…);String name = ((Musical)play).getComposer() ;

Page 75: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

• An array of Production references:

Production productions[] = new Production[3]; // holds 3 Production referencesproductions[0] = new Film (…);productions[1] = new Play(…);productions[2] = new Musical(…);

• Each of these assignments is legal: Film is-a Production; Play is-a Production; and Musical is-a Production.

• The method calls:

productions[0].getBoxOfficeGross() and productions[2].getComposer()

generate errors.

• The references productions[0] and productions[2] know nothing of the methods getBoxOfficeGross() and getComposer().

Page 76: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting and Downcasting

• A downcast fixes these errors and produces the desired results:

– ((Film)productions[0]).getBoxOfficeGross()– ((Musical)productions[2]).getComposer()

• To invoke a derived class method through an object of the base class, a downcast is necessary.

Page 77: Java Programming: From the Ground Up Chapter 12: Inheritance

The instanceof operator

• Like && and ||, instanceof is a boolean operator that requires two operands.

• The form of the instanceof operator is:

object instanceof class 

where object is any object and class is any class name.

• If object belongs to or is derived from class then instanceof returns true otherwise instanceof returns false.

•  Play play = new Play();Musical musical = new Musical();Film film = new Film();

film instanceof Film returns true,film instanceof Production returns true,musical instanceof Play returns true,musical instanceof Film returns false, andmusical instanceof Production returns true.

Page 78: Java Programming: From the Ground Up Chapter 12: Inheritance

The instanceof operator

Problem Statement:

• Write a single method:

– int getData(Production p)

that returns the box office gross for a Film, or the number of performances for a Play.

• If an object p is neither a Film nor a Play, then getData(p) returns –1.

Page 79: Java Programming: From the Ground Up Chapter 12: Inheritance

The instanceof operator

Java Solution:

• The reference, p, passed to getData(...) refers to a Production object, which can be either a Film object or a Play object.

• getData(...) accepts a Film reference, a Play reference, or even a Musical reference, because each of these is-a Production.

• The getData(...) method determines whether its parameter refers to a Film or a Play by utilizing the instanceof operator.

Page 80: Java Programming: From the Ground Up Chapter 12: Inheritance

The instanceof operator

1. public class InstanceOfDemo2. {3. public static int getData(Production p) // Parameter is Production

reference4. {5. if (p instanceof Film)6. return ((Film)p).getBoxOfficeGross(); // note the downcast7. else if (p instanceof Play)8. return ((Play)p).getPerformances(); // note the downcast9. else10. return -1;11. }

Page 81: Java Programming: From the Ground Up Chapter 12: Inheritance

The instanceof operator

12. public static void main(String[] args)13. {14. Production productions[] = new Production[3];15. productions[0] = new Film("Titanic", "James Cameron",

"James Cameron", 2245);16. productions[1] = new Play("Rumors", "Gene Saks", "Neil Simon", 535);17. productions[2] = new Musical("Pippin", "Bob Fosse","Roger O. Hirson",18. "Stephen Schwartz","Stephen Schwartz",1944);19. for(int i = 0; i <3; i++)20. {21. System.out.print(productions[i].getTitle()+": " +

getData(productions[i]));22. if (productions[i] instanceof Play)23. System.out.println(" performances");24. else25. System.out.println(" million dollars");26. }27. }28. }

Page 82: Java Programming: From the Ground Up Chapter 12: Inheritance

Everything Inherits: the Object Class

• The package java.lang, which is automatically imported into every application, contains Java’s Object class.

• Every class is a subclass of Object.

• Every class is derived from Object. •  • Every class inherits methods:

– public boolean equals(Object object), and – public String toString()

from Object.

Page 83: Java Programming: From the Ground Up Chapter 12: Inheritance

Everything Inherits: the Object Class

• Because every class extends Object, every class can be upcast to Object:

– Object remote = new Remote();

– Object film = new Film();

• Remote is-a Object and Film is-a Object.

Page 84: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheriting From Object: the equals(Object p) Method

• Every class inherits

– boolean equals(Object p)

from Object.

• The equals(...) method accepts a single Object argument p and returns true or false.

• Like the == operator, the equals(...) method tests whether or not two references are the same.

 • Every class inherits equals(...) from Object but each class also has the

option of overriding the inherited equals(...).

• For instance, String inherits equals(...) from Object, and conveniently overrides the inherited method.

Page 85: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheriting From Object: the equals(Object p) Method

• String overrides the equals(...) method with a version that compares characters, not references.

1. String s =new String( "Bingo!");2. String t = new String("Bingo!");3. System.out.println(s.equals(t)); // returns true4. System.out.println(s == t); // returns false

• As a general rule, to determine whether or not two objects of a class are equal based on some criteria other than references, a class should override:

boolean equals(Object o),

which is inherited from Object.

Page 86: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheriting From Object: the toString() Method

• Like equals(...), every object inherits the method:

String toString()

from mother Object.

• The inherited version of toString() is not particularly useful.

• As passed down from Object, toString() returns the class name of the calling object along with a “system number.”

Page 87: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheriting From Object: the toString() Method

• The following main(...) method includes a call to toString() that is inherited by Film:

public static void main(String[] args){

Film film = new Film("Star Wars", "George Lucas","George Lucas", 1172); System.out.println(film.toString());}

• The output produced by this segment is :

Film@82ba41

Page 88: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheriting From Object: the toString() Method

Problem statement:

• Override the toString() method inherited by Production so that the method returns the title attribute of an object in the Production hierarchy.

Page 89: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheriting From Object: the toString() Method

Java Solution:

• To override the toString() method that Production inherits from Object, include the following method in the Production class:

1. public String toString()2. {3. return title ;4. }

• The new toString() method returns a String containing the title attribute of a Production object.

• Naturally, all subclasses of Production inherit this method.

Page 90: Java Programming: From the Ground Up Chapter 12: Inheritance

Inheriting From Object: the toString() Method

• The toString() method is automatically called when a reference is passed to println().

• This means the statements:

System.out.println(film.toString()); and

System.out.println(film);

produce the same output.

Page 91: Java Programming: From the Ground Up Chapter 12: Inheritance

Interfaces

• An interface is a named collection of static constants and abstract methods.

• An interface specifies certain actions or behaviors of a class but not their implementations.

• The interface, Geometry, consists of one static constant and two abstract methods.

1. public interface Geometry2. {3. public static final double PI = 3.14159;4. public abstract double area();5. public abstract double perimeter();6. }

Page 92: Java Programming: From the Ground Up Chapter 12: Inheritance

Interfaces

• Unlike a class:

– all methods of a interface are public,

– all methods of an interface are abstract, i.e., there are no implementations at all, and

– an interface has no instance variables.

• Like an abstract class, an interface cannot be instantiated.

• In contrast to an abstract class, a class does not extend an interface. Instead, a class implements an interface.

Page 93: Java Programming: From the Ground Up Chapter 12: Inheritance

Interfaces

Problem Statement

Define Circle, Square, and Triangle classes each of which implements theGeometry interface.

Java Solution

• Because the following classes implement Geometry, each class is required to implement the area() and perimeter() methods.

• For simplicity, the usual getter and setter methods are not included.

Page 94: Java Programming: From the Ground Up Chapter 12: Inheritance

Circle

1. public class Circle implements Geometry2. {3. private double radius;4. public Circle()5. {6. radius = 0.0;7. }8. public Circle (double r)9. {10. radius = r;11. }12. public double perimeter()13. {14. return 2*PI*radius;15. }16. public double area() 17. {18. return PI*radius*radius; 19. }20. }

Page 95: Java Programming: From the Ground Up Chapter 12: Inheritance

Square

1. public class Square implements Geometry

2. {3. private double side;4. public Square()5. {6. side = 0.0;7. }8. public Square (double s) 9. {10. side = s;11. }12. public double perimeter()13. {14. return 4*side;15. }16. public double area() 17. {18. return side*side; 19. }20. }

Page 96: Java Programming: From the Ground Up Chapter 12: Inheritance

Triangle

1. public class Triangle implements Geometry

2. {3. // three sides a,b,c 4. private double a,b,c;

5. public Triangle()6. {7. a=b=c= 0.0;8. }

9. public Triangle (double a1,10. double b1, double c1)11. {12. a = a1;13. b = b1;14. c = c1;15. }

16. public double perimeter()17. {18. return a+b+c;19. }

20. public double area() 21. {22. double s =(a+b+c)/2.0; 23. return

Math.sqrt(s*(s-a)*(s-b)*(s-c)); 24. }25. }

Page 97: Java Programming: From the Ground Up Chapter 12: Inheritance

Interfaces

Discussion:

• The three classes do not extend Geometry; each implements Geometry.

• Geometry is not a class; Geometry is an interface and a class implements an interface.

• Each class must implement both of Geometry’s methods, area() and perimeter().

• The constant PI used in Circle is defined in the Geometry interface.

Page 98: Java Programming: From the Ground Up Chapter 12: Inheritance

An Interface is a Contract

• An interface is a contract.

• An interface specifies a set of responsibilities, actions, or behaviors for any class that implements it.

• A class that implements an interface must implement all the methods of the interface, or be tagged as abstract.

Page 99: Java Programming: From the Ground Up Chapter 12: Inheritance

Upcasting to an Interface

• A derived class can be upcast to any one of its interfaces.

• In particular, Circle, Square, and Triangle objects can be upcast to Geometry:

Geometry[] shapes = new Geometry[3]; // Geometry is an interface

shapes[0] = new Circle(2.0);shapes [1] = new Square(5.0);shapes [2] = new Triangle(8.0,5.0,5.0);

Page 100: Java Programming: From the Ground Up Chapter 12: Inheritance

The Comparable Interface

• Java also provides a large number of ready-made interfaces.

• Among one of the most useful Java-supplied interfaces is the Comparable interface.

•  • Comparable is an interface with just one method,

compareTo(...): 

public interface Comparable{

int compareTo(Object o);}

compareTo(...) returns an integer and accepts any Object reference as an argument.

Page 101: Java Programming: From the Ground Up Chapter 12: Inheritance

The Comparable Interface

• A class that implements the Comparable interface implements compareTo(...) so that

– a.CompareTo(b) returns a negative integer, if a is “less than” b,

– a.CompareTo(b) returns 0, if a “equals” b, and– a.CompareTo(b) returns a positive integer, if a is

“greater than” b.

• A class that implements Comparable is advertising to its clients that its objects can be “compared”.

Page 102: Java Programming: From the Ground Up Chapter 12: Inheritance

The Comparable Interface

Problem statement:

• Redefine the Production hierarchy so that Film and Play implement the Comparable interface.

• Compare two Film objects based on the value of boxOfficeGross and two Play objects according to the number of performances.

Page 103: Java Programming: From the Ground Up Chapter 12: Inheritance

The Comparable Interface

Because Play implements Comparable, Play must implements compareTo(…).

1. public class Play extends Production implements Comparable2. {3. // exactly as before (Play) with the addition of compareTo()

4. public int compareTo(Object p) // from the Comparable interface5. {6. if ( !(p instanceof Play) ) // p must belong to Play7. {8. System.out.println("Error: Object does not belong to Play");9. System.exit(0);10. }11. if (performances < ((Play)p).performances)

// p must be downcast to Play12. return -1;13. if (performances > ((Play)p).performances)14. return 1;15. return 0;16. }17. }

Page 104: Java Programming: From the Ground Up Chapter 12: Inheritance

The Comparable Interface

The Film class also implements Comparable and is outfitted with its own compareTo() method.

1. public class Film extends Production implements Comparable2. {3. // exactly as before with the addition of compareTo()

4. public int compareTo(Object p) // from the Comparable interface5. {6. if ( !(p instanceof Film)) // p must belong to Film7. {8. System.out.println("Error: object must belong to Film");9. System.exit(0);10. }11. if (boxOfficeGross < ((Film)p).boxOfficeGross) // note downcast 12. return -1;13. if (boxOfficeGross> ((Film)p).boxOfficeGross) // note downcast14. return 1;15. return 0;16. }17.}

Page 105: Java Programming: From the Ground Up Chapter 12: Inheritance

The Comparable Interface

• Because Play and Film implement Comparable, a Play or Film reference can be upcast to Comparable.

• For example, the statement: 

Comparable play = new Play();is legal.

Page 106: Java Programming: From the Ground Up Chapter 12: Inheritance

A Generic Sort

• Classes that implement the Comparable interface can utilize a general sort routine that orders objects based on the implementation of compareTo(...).

Problem Statement:

• Devise a generic sort method that can be used to sort objects of any class that implements the Comparable interface.

Page 107: Java Programming: From the Ground Up Chapter 12: Inheritance

A Generic Sort

Java Solution

Selection sort, (also called max sort):

• First, sort(…) determines the largest value (max) that is stored in array x and swaps max with x[size-1]; then sort(...) finds the next largest value and swaps that value with x[size-2], etc.

• Selection sort places the largest value in its proper place, then the second largest value in its place, then the third largest value, continuing until the array is sorted.

Page 108: Java Programming: From the Ground Up Chapter 12: Inheritance

A Generic Sort1. public class SelectionSort 2. {3. public static void sort(Comparable[] x, int size) // accepts an array of Comparable objects4. {5. Comparable max; // max belongs to a class that implements Comparable6. int maxIndex;7. for (int i=size-1; i>=1; i--)8. {9. // Find the maximum in the x[0..i]10. max = x[i]; // the "current" maximum is x[i]11. maxIndex = i; // the index of the "current" maximum

12. for (int j=i-1; j>=0; j--) // compare other values to "current" maximum13. {14. if (max.compareTo(x[j]) < 0) // if max is "less than" x[i]15. {16. max = x[j]; // a "new" maximum17. maxIndex = j;18. }19. }20. if (maxIndex != i) // place the maximum in its proper position21. {22. x[maxIndex] = x[i];23. x[i] = max;24. }25. }26. }27. }

Page 109: Java Programming: From the Ground Up Chapter 12: Inheritance

A Generic Sort

Discussion:

• The reference passed to sort(...) has type Comparable.

• Object references of any class that implements the Comparable interface can be upcast to Comparable.

• And, Comparable objects can be sorted with this method.

Page 110: Java Programming: From the Ground Up Chapter 12: Inheritance

Composition and the has-a Relationship

• Inheritance, as you know, is characterized by an is-a relationship:

– a Square is-a Shape, – a RightTriangle is-a Shape, – a Film is-a Production,– a Dog is-an Animal, and– a Bloodhound is-a Dog.

• Often times, classes are related, but not via an is-a

relationship.

• In these cases, upcasting is not of any apparent value.

Page 111: Java Programming: From the Ground Up Chapter 12: Inheritance

Composition and the has-a Relationship

public class Person{ private String name: private String address; //etc.}

public class BankAccount{ private String accountNumber; private double balance; ... public double balance() //etc.}

• Inheritance is not natural.

• A person is not a BankAccount and a BankAccount is not a Person. • There is no apparent or logical reason to consider a Person a type of BankAccount or vice versa.

Page 112: Java Programming: From the Ground Up Chapter 12: Inheritance

Composition and the has-a Relationship

• If every Person possesses a BankAccount.

• A BankAccount reference can be declared an instance variable of the Person class.

• In such a case, the relationship between the Person and the BankAccount classes is a has-a relationship.

• A Person has-a BankAccount.

• And, a Person class can be defined with a BankAccount attribute.

Page 113: Java Programming: From the Ground Up Chapter 12: Inheritance

Composition and the has-a Relationship

public class Person{

private String name:private String address;private BankAccount account;// etc.

}

• The relationship between Person and BankAccount is an example of composition - a relationship in which one object is composed of other objects.

• As an is-a relationship indicates inheritance, a has-a relationship signals composition.

•  • Inheritance implies an extension of functionality and the ability to upcast;

composition indicates ownership.

• Inheritance and composition are very different concepts; the two should not be confused.