Presentation is loading. Please wait.

Presentation is loading. Please wait.

Improving structure with inheritance (Chapters 8 and 9)

Similar presentations


Presentation on theme: "Improving structure with inheritance (Chapters 8 and 9)"— Presentation transcript:

1 Improving structure with inheritance (Chapters 8 and 9)

2 2 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables

3 3 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The DoME example "Database of Multimedia Entertainment" stores details about CDs and DVDs –CD: title, artist, # tracks, playing time, got- it, comment –DVD: title, director, playing time, got-it, comment allows (later) to search for information or print lists

4 4 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling DoME objects

5 5 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling DoME classes top half shows fields bottom half shows methods

6 6 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling DoME object model

7 7 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Class diagram

8 8 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling CD source code public class CD { private String title; private String title; private String artist; private String artist; private String comment; private String comment; public CD (String theTitle, String theArtist) public CD (String theTitle, String theArtist) { title = theTitle; title = theTitle; artist = theArtist; artist = theArtist; comment = " "; comment = " "; } public void setComment (String newComment) public void setComment (String newComment) {... } {... } public String getComment () public String getComment () {... } {... } public void print () public void print () {... } {... }... other methods... other methods} incomplete (comments!) [ ]

9 9 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling DVD source code public class DVD { private String title; private String title; private String director; private String director; private String comment; private String comment; public DVD (String theTitle, String theDirector) public DVD (String theTitle, String theDirector) { title = theTitle; title = theTitle; director = theDirector; director = theDirector; comment = " "; comment = " "; } public void setComment (String newComment) public void setComment (String newComment) {... } {... } public String getComment () public String getComment () {... } {... } public void print () public void print () {... } {... }... other methods... other methods} incomplete (comments!) [ ]

10 10 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling class Database { private ArrayList cds ; private ArrayList cds ; private ArrayList dvds ; private ArrayList dvds ;... addCD, addDVD... addCD, addDVD public void list () public void list () { for( CD cd : cds ) { for( CD cd : cds ) { cd.print (); cd.print (); System.out.println (); // empty line between items System.out.println (); // empty line between items } for( DVD dvd : dvds ) { for( DVD dvd : dvds ) { dvd.print (); dvd.print (); System.out.println (); // empty line between items System.out.println (); // empty line between items } }} Database source code

11 11 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Critique of DoME code duplication –CD and DVD classes very similar (large part are identical) –makes maintenance difficult/more work –introduces danger of bugs through incorrect maintenance code duplication also in Database class

12 12 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using inheritance

13 13 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Using inheritance define one superclass : Item define subclasses for Video and CD the superclass defines common attributes the subclasses inherit the superclass attributes the subclasses add own attributes

14 14 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Inheritance hierarchies

15 15 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Inheritance in Java public class Item {......} public class CD extends Item {......} public class DVD extends Item {......} no change here change here

16 16 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Superclass public class Item { private String title; private String title; private int playingTime; private int playingTime; private boolean gotIt; private boolean gotIt; private String comment; private String comment;... constructors and methods... constructors and methods}

17 17 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Subclasses public class CD extends Item { private String artist; private int numberOfTracks;... constructors and methods } public class DVD extends Item { private String director;... constructors and methods }

18 18 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class Item { private String title; private String title; private int playingTime; private int playingTime; private boolean gotIt; private boolean gotIt; private String comment; private String comment; /** /** * Initialise the fields of the item. * Initialise the fields of the item. */ */ public Item (String theTitle, int time) public Item (String theTitle, int time) { title = theTitle; title = theTitle; playingTime = time; playingTime = time; gotIt = false; gotIt = false; comment = ""; comment = ""; }... methods... methods} Inheritance and constructors

19 19 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class CD extends Item { private String artist; private String artist; private int numberOfTracks; private int numberOfTracks; /** /** * Constructor for objects of class CD * Constructor for objects of class CD */ */ public CD (String theTitle, String theArtist, public CD (String theTitle, String theArtist, int tracks, int time) int tracks, int time) { super (theTitle, time); super (theTitle, time); artist = theArtist; artist = theArtist; numberOfTracks = tracks; numberOfTracks = tracks; }... methods... methods} Inheritance and constructors

20 20 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Superclass constructor call Subclass constructors must always contain a 'super' call. Subclass constructors must always contain a 'super' call. If none is written, the compiler inserts one (without parameters) If none is written, the compiler inserts one (without parameters) –this works only, if the superclass has a constructor without parameters The 'super' call must be the first statement in the subclass constructor. The 'super' call must be the first statement in the subclass constructor.

21 21 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Adding more item types

22 22 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Deeper hierarchies

23 23 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review (so far) Inheritance (so far) helps with: Avoiding code duplication Code reuse Easier maintenance Extendibility

24 24 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling public class Database { private ArrayList items; private ArrayList items; /** /** * Construct an empty Database. * Construct an empty Database. */ */ public Database () public Database () { items = new ArrayList (); items = new ArrayList (); } /** /** * Add an item to the database. * Add an item to the database. */ */ public void addItem (Item theItem) public void addItem (Item theItem) { items.add (theItem); items.add (theItem); }... list... list} New Database source code avoids code duplication in client!

25 25 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling /** * Print a list of all currently stored CDs and * Print a list of all currently stored CDs and * DVD s to the text terminal. * DVD s to the text terminal. */ */ public void list() { for( Item item : items ) { for( Item item : items ) { item.print(); item.print(); // Print an e mpty line between items // Print an e mpty line between items System.out.println(); System.out.println(); }} New Database source code

26 26 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Subtyping First, we had: public void addCD (CD theCD) public void addCD (CD theCD) public void addVideo ( DVD the DVD ) public void addVideo ( DVD the DVD ) Now, we have: public void addItem (Item theItem) public void addItem (Item theItem) We call this method with: DVD my DVD = new DVD (...); DVD my DVD = new DVD (...); database.addItem (my DVD ); database.addItem (my DVD );

27 27 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Subclasses and subtyping Classes define types. Classes define types. Subclasses define subtypes. Subclasses define subtypes. Objects of subclasses can be used where objects of supertypes are required. (This is called substitution.) Objects of subclasses can be used where objects of supertypes are required. (This is called substitution.)

28 28 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Subtyping and assignment Vehicle v1 = new Vehicle(); Vehicle v2 = new Car(); Vehicle v3 = new Bicycle(); subclass objects may be assigned to superclass variables

29 29 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Subtyping and parameter passing public class Database { public void addItem(Item theItem) public void addItem(Item theItem) {...... }} DVD dvd = new DVD(...); CD cd = new CD(...); database.addItem(dvd); database.addItem(cd); subclass objects may be passed to superclass parameters

30 30 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Object diagram

31 31 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Class diagram

32 32 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Polymorphic variables Object variables in Java are polymorphic. (They can hold objects of more than one type.) They can hold objects of the declared type, or of subtypes of the declared type.

33 33 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Casting Can assign subtype to supertype. Can assign subtype to supertype. Cannot assign supertype to subtype! Vehicle v; Car c = new Car(); v = c; // correct; c = v; // will not compile Cannot assign supertype to subtype! Vehicle v; Car c = new Car(); v = c; // correct; c = v; // will not compile Casting fixes this : c = (Car) v; // compiles OK (run-time error if v is not a Car !) Casting fixes this : c = (Car) v; // compiles OK (run-time error if v is not a Car !)

34 34 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Casting An object type in parentheses. An object type in parentheses. Used to overcome 'type loss'. Used to overcome 'type loss'. The object is not changed in any way. The object is not changed in any way. A run-time check is made to ensure the object really is of that type: A run-time check is made to ensure the object really is of that type: –ClassCastException if it isn't! Use it sparingly. Use it sparingly.

35 35 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The Object class All classes inherit from Object.

36 36 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Polymorphic collections All collections are polymorphic. All collections are polymorphic. We can have collections of. public void add (Object element) public Object get (int index) We can have collections of. public void add (Object element) public Object get (int index)

37 37 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Collections and primitive types All objects can be entered into such collections... All objects can be entered into such collections...... because such collections accept elements of type Object...... because such collections accept elements of type Object...... and all classes are subtypes of Object.... and all classes are subtypes of Object. Great! But what about simple types? Great! But what about simple types?

38 38 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Wrapper classes Primitive types (int, char, etc) are not objects. To collect them, they must be wrapped into an object! Wrapper classes exist for all simple types: simple typewrapper class intInteger floatFloat charCharacter...

39 39 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Wrapper classes int i = 18; Integer iwrap = new Integer(i);... int value = iwrap.intValue(); wrap the value unwrap it In practice, autoboxing and unboxing mean we don't often have to do this.

40 40 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Autoboxing and unboxing private ArrayList markList; … public void storeMark (int mark) { markList.add (mark); } int firstMark = markList.remove (0); autoboxing unboxing

41 41 private ArrayList markList; … public void storeMark (int mark) { markList.add (new Integer (mark)); } int firstMark = markList.remove(0).intValue(); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Autoboxing and unboxing so we don’t have to write this

42 42 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review so far... Inheritance allows the definition of classes as extensions of other classes. Inheritance –avoids code duplication –allows code reuse –simplifies the code –simplifies maintenance and extending Variables can hold subtype objects. Subtypes can be used wherever supertype objects are expected (substitution).

43 More about inheritance Exploring polymorphism (Chapter 9)

44 44 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to be covered method polymorphism static and dynamic type overriding dynamic method lookup protected access

45 45 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The inheritance hierarchy

46 46 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Conflicting output CD: A Swingin' Affair (64 mins)* Frank Sinatra Frank Sinatra tracks: 16 tracks: 16 my favourite Sinatra album my favourite Sinatra album DVD: O Brother, Where Art Thou? (106 mins) Joel & Ethan Coen Joel & Ethan Coen The Coen brothers’ best movie! The Coen brothers’ best movie! title: A Swingin' Affair (64 mins)* my favourite Sinatra album my favourite Sinatra album title: O Brother, Where Art Thou? (106 mins) The Coen brothers’ best movie! The Coen brothers’ best movie! What we want What we have

47 47 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The problem The print method in Item only prints the common fields. The print method in Item only prints the common fields. Inheritance is a one-way street: Inheritance is a one-way street: –A subclass inherits the superclass fields. –The superclass knows nothing about its subclass’s fields.

48 48 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Attempting to solve the problem Place print where it has access to the information it needs. Each subclass has its own version. But Item ’s fields are private. Database cannot find a print method in Item.

49 49 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Static type and dynamic type A more complex type hierarchy needs further concepts to describe it. Some new terminology: –static type –dynamic type –method dispatch/lookup

50 50 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Static and dynamic type Car c1 = new Car(); What is the type of c1? Vehicle v1 = new Car(); What is the type of v1?

51 51 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Static and dynamic type The declared type of a variable is its static type. The declared type of a variable is its static type. The type of the object a variable refers to is its dynamic type. The type of the object a variable refers to is its dynamic type. The compiler’s job is to check for static-type violations. for(Item item : items) { item.print(); // Compile-time error. } The compiler’s job is to check for static-type violations. for(Item item : items) { item.print(); // Compile-time error. }

52 52 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Overriding: the solution print method in both super- and subclasses. Satisfies both static and dynamic type checking.

53 53 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Overriding Superclass and subclass define methods with the same signature. Each has access to the fields of its class. Superclass satisfies static type check. Subclass method is called at runtime – it overrides the superclass version. What becomes of the superclass version?

54 54 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Method lookup No inheritance or polymorphism. The obvious method is selected.

55 55 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Method lookup Inheritance but no overriding. The inheritance hierarchy is ascended, searching for a match.

56 56 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Method lookup Polymorphism and overriding. The ‘first’ version found is used.

57 57 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Method lookup summary The variable is accessed. The object stored in the variable is found. The class of the object is found. The class is searched for a method match. If no match is found, the superclass is searched. This is repeated until a match is found, or the class hierarchy is exhausted. Overriding methods take precedence.

58 58 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Super call in methods Overridden methods are hidden... Overridden methods are hidden...... but we often still want to be able to call them.... but we often still want to be able to call them. An overridden method can be called from the method that overrides it. An overridden method can be called from the method that overrides it. –super.print (...) –Compare with the use of super in constructors.

59 59 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Calling an overridden method public class CD extends Item {... public void print () public void print () { super.print (); super.print (); System.out.println (" " + artist); System.out.println (" " + artist); System.out.println (" tracks: " + System.out.println (" tracks: " + numberOfTracks); numberOfTracks); }......}

60 60 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Method polymorphism We have been discussing polymorphic method dispatch. We have been discussing polymorphic method dispatch. A polymorphic variable can store objects of varying types. A polymorphic variable can store objects of varying types. Method calls are. Method calls are polymorphic. –The actual method called depends on the dynamic object type.

61 61 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling The Object class’s methods Methods in Object are inherited by all classes. Methods in Object are inherited by all classes. Any of these may be overridden. Any of these may be overridden. The toString method (of Object ) is commonly overridden: The toString method (of Object ) is commonly overridden: –public String toString () –Returns a string representation of the object.

62 62 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Overriding toString public class Item {...... public String toString () public String toString () { String line1 = title + String line1 = title + " (" + playingTime + " mins)"); " (" + playingTime + " mins)"); if (gotIt) { if (gotIt) { return line1 + "*\n" + " " + return line1 + "*\n" + " " + comment + "\n"); comment + "\n"); } else { } else { return line1 + "\n" + " " + return line1 + "\n" + " " + comment + "\n"); comment + "\n"); } }......}

63 63 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Overriding toString Explicit print methods can often be omitted from a class: Explicit print methods can often be omitted from a class: System.out.println (item.toString()); System.out.println (item.toString()); Calls to println with just an object automatically result in toString being called: Calls to println with just an object automatically result in toString being called: System.out.println (item); System.out.println (item);

64 64 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Protected access Private access in the superclass may be too restrictive for a subclass. Private access in the superclass may be too restrictive for a subclass. The closer inheritance relationship is supported by protected access: protected things (fields, constructors, methods, etc.) may be used by sub-classes. The closer inheritance relationship is supported by protected access: protected things (fields, constructors, methods, etc.) may be used by sub-classes. Protected access is more restricted than public access. Protected access is more restricted than public access. We still recommend keeping fields private. We still recommend keeping fields private. –Define protected accessors and mutators for sub-classes to use.

65 65 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Access levels

66 66 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Review The declared type of a variable is its static type: The declared type of a variable is its static type: –Compilers check static types. The type of an object is its dynamic type: The type of an object is its dynamic type: –Dynamic types are used at runtime. Methods may be overridden in a subclass. Methods may be overridden in a subclass. Method lookup starts with the dynamic type. Method lookup starts with the dynamic type. Protected access reflects inheritance. Protected access reflects inheritance.


Download ppt "Improving structure with inheritance (Chapters 8 and 9)"

Similar presentations


Ads by Google