+ All Categories
Home > Documents > Improving structure with inheritance (Chapters 8 and 9)

Improving structure with inheritance (Chapters 8 and 9)

Date post: 19-Dec-2015
Category:
Upload: charles-campbell
View: 224 times
Download: 1 times
Share this document with a friend
Popular Tags:
66
Improving structure with inheritance (Chapters 8 and 9)
Transcript
Page 1: Improving structure with inheritance (Chapters 8 and 9)

Improving structure with inheritance

(Chapters 8 and 9)

Page 2: Improving structure with inheritance (Chapters 8 and 9)

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

Page 3: Improving structure with inheritance (Chapters 8 and 9)

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

Page 4: Improving structure with inheritance (Chapters 8 and 9)

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

DoME objects

Page 5: Improving structure with inheritance (Chapters 8 and 9)

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

Page 6: Improving structure with inheritance (Chapters 8 and 9)

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

DoME object model

Page 7: Improving structure with inheritance (Chapters 8 and 9)

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

Class diagram

Page 8: Improving structure with inheritance (Chapters 8 and 9)

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

CD source code

public class CDpublic 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 public CD (String theTitle, String theArtist)theArtist) {{ title = theTitle;title = theTitle; artist = theArtist;artist = theArtist; comment = "<no comment>";comment = "<no 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!)[ ]

Page 9: Improving structure with inheritance (Chapters 8 and 9)

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

DVD source code

public class DVDpublic 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 public DVD (String theTitle, String theDirector)theDirector) {{ title = theTitle;title = theTitle; director = theDirector;director = theDirector; comment = "<no comment>";comment = "<no 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!)[ ]

Page 10: Improving structure with inheritance (Chapters 8 and 9)

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

class Database {class Database {

private ArrayList<CD> cdsprivate ArrayList<CD> cds;; private ArrayList<DVD> dvdsprivate ArrayList<DVD> dvds;;

... addCD, addDVD... addCD, addDVD

public void list ()public void list () { { for(for(CD cd : cdsCD cd : cds) {) { cd.printcd.print ();(); System.out.printlnSystem.out.println (); // empty line between items(); // empty line between items }}

for(for(DVD dvd : dvdsDVD dvd : dvds) {) { dvddvd.print.print ();(); System.out.printlnSystem.out.println (); // empty line between items(); // empty line between items }} }}

}}

Database source code

Page 11: Improving structure with inheritance (Chapters 8 and 9)

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

Page 12: Improving structure with inheritance (Chapters 8 and 9)

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

Using inheritance

Page 13: Improving structure with inheritance (Chapters 8 and 9)

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

Page 14: Improving structure with inheritance (Chapters 8 and 9)

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

Inheritance hierarchies

Page 15: Improving structure with inheritance (Chapters 8 and 9)

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

Inheritance in Java

public class Itempublic class Item{{ ......}}

public class CD extends Itempublic class CD extends Item{{ ......}}

public class public class DVDDVD extends Item extends Item {{ ......}}

no change here

change here

Page 16: Improving structure with inheritance (Chapters 8 and 9)

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

Superclass

public class Itempublic 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 methodsconstructors and methods

}}

Page 17: Improving structure with inheritance (Chapters 8 and 9)

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}

Page 18: Improving structure with inheritance (Chapters 8 and 9)

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

public class Itempublic 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 Itempublic Item (String theTitle, int time)(String theTitle, int time) {{ title = theTitle;title = theTitle; playingTime = time;playingTime = time; gotIt = false;gotIt = false; comment = "";comment = ""; }}

... ... methodsmethods

}}

Inheritance and

constructors

Page 19: Improving structure with inheritance (Chapters 8 and 9)

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

public class CD extends Itempublic 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 CDpublic CD ((String theTitleString theTitle, String, String theArtist, theArtist, int tracks, int tracks, int timeint time)) {{ supersuper (theTitle, time);(theTitle, time); artist = theArtist;artist = theArtist; numberOfTracks = tracks;numberOfTracks = tracks; }}

... ... methods methods

}}

Inheritance and

constructors

Page 20: Improving structure with inheritance (Chapters 8 and 9)

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

Superclass constructor call

• Subclass constructors must Subclass constructors must always contain a 'always contain a 'supersuper' call.' call.

• If none is written, the compiler If none is written, the compiler inserts one (without parameters)inserts one (without parameters)– this works only, if the superclass has this works only, if the superclass has

a constructor without parametersa constructor without parameters• The 'The 'supersuper' call must be the first ' call must be the first

statement in the subclass statement in the subclass constructor.constructor.

Page 21: Improving structure with inheritance (Chapters 8 and 9)

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

Adding more item types

Page 22: Improving structure with inheritance (Chapters 8 and 9)

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

Deeper hierarchies

Page 23: Improving structure with inheritance (Chapters 8 and 9)

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

Page 24: Improving structure with inheritance (Chapters 8 and 9)

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

public class Databasepublic class Database{{ private ArrayListprivate ArrayList<Item><Item> items; items;

/**/** * Construct an empty Database.* Construct an empty Database. */*/ public Databasepublic Database ()() {{ items = new ArrayListitems = new ArrayList<Item> <Item> ();(); }}

/**/** * Add an item to the database.* Add an item to the database. */*/ public void addItempublic void addItem (Item theItem)(Item theItem) {{ items.additems.add (theItem);(theItem); }}

...... list list}}

New Database source code

avoids code duplication in client!

Page 25: Improving structure with inheritance (Chapters 8 and 9)

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 * * DVDDVDs to the text terminal.s to the text terminal. */*/public void list()public void list(){{ for(for(Item item : itemsItem item : items) {) { item.print();item.print(); // // Print an ePrint an empty line between itemsmpty line between items System.out.println(); System.out.println(); }}}}

New Database source code

Page 26: Improving structure with inheritance (Chapters 8 and 9)

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

Subtyping

First, we had:First, we had:

public void addCDpublic void addCD (CD theCD)(CD theCD) public void addVideopublic void addVideo ((DVDDVD the theDVDDVD))

Now, we have:Now, we have:

public void addItempublic void addItem (Item theItem)(Item theItem)

We call this method with:We call this method with:

DVDDVD my myDVDDVD = new = new DVD DVD (...);(...); database.addItemdatabase.addItem (my(myDVDDVD););

Page 27: Improving structure with inheritance (Chapters 8 and 9)

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 Objects of subclasses can be

used where objects of supertypes used where objects of supertypes are required.are required.(This is called (This is called substitutionsubstitution.).)

Page 28: Improving structure with inheritance (Chapters 8 and 9)

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

Subtyping and assignment

Vehicle v1 = new Vehicle();Vehicle v1 = new Vehicle();Vehicle v2 = new Car();Vehicle v2 = new Car();Vehicle v3 = new Bicycle();Vehicle v3 = new Bicycle();

subclass subclass objects may be objects may be assigned to assigned to superclass superclass variablesvariables

Page 29: Improving structure with inheritance (Chapters 8 and 9)

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

Subtyping and parameter passing

public class Databasepublic class Database{{ public void addItem(Item theItem)public void addItem(Item theItem) {{ ...... }}}}

DVDDVD dvddvd = new = new DVDDVD(...);(...);CD cd = new CD(...);CD cd = new CD(...);

database.addItem(database.addItem(dvddvd););database.addItem(cd);database.addItem(cd);

subclass subclass objects may be objects may be passed to passed to superclass superclass parametersparameters

Page 30: Improving structure with inheritance (Chapters 8 and 9)

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

Object diagram

Page 31: Improving structure with inheritance (Chapters 8 and 9)

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

Class diagram

Page 32: Improving structure with inheritance (Chapters 8 and 9)

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.

Page 33: Improving structure with inheritance (Chapters 8 and 9)

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!Cannot assign supertype to subtype!

Vehicle v;Vehicle v; Car c = new Car(); Car c = new Car(); v = c; // v = c; // correct;correct; c = v; // c = v; // will not compilewill not compile

• Casting fixes thisCasting fixes this::

c = (Car) v; // compiles OKc = (Car) v; // compiles OK

(run-time error if (run-time error if vv is not a is not a CarCar!)!)

Page 34: Improving structure with inheritance (Chapters 8 and 9)

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 The object is not changed in any

way.way.• A run-time check is made to ensure A run-time check is made to ensure

the object really is of that type:the object really is of that type:– ClassCastExceptionClassCastException if it isn't! if it isn't!

• Use it sparingly.Use it sparingly.

Page 35: Improving structure with inheritance (Chapters 8 and 9)

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

The Object class

All classes inherit from Object.

Page 36: Improving structure with inheritance (Chapters 8 and 9)

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 We can have collections of <Object><Object>..

public void add (Object element)public void add (Object element)public Object get (int index)public Object get (int index)

Page 37: Improving structure with inheritance (Chapters 8 and 9)

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 All objects can be entered into such collections ...such collections ...

• ... because such collections ... because such collections accept elements of type accept elements of type ObjectObject......

• ... and all classes are subtypes of ... and all classes are subtypes of ObjectObject..

• Great! But what about simple Great! But what about simple types?types?

Page 38: Improving structure with inheritance (Chapters 8 and 9)

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 type wrapper classint Integerfloat Floatchar Character... ...

Page 39: Improving structure with inheritance (Chapters 8 and 9)

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

Wrapper classes

int i = 18; int i = 18; Integer iwrap = new Integer(i); Integer iwrap = new Integer(i); ......int value = iwrap.intValue();int value = iwrap.intValue();

wrap the value

unwrap it

In practice, autoboxing and unboxing mean we don't often have to do

this.

Page 40: Improving structure with inheritance (Chapters 8 and 9)

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

Autoboxing and unboxingprivate ArrayList<Integer> markList;

public void storeMark (int mark)

{

markList.add (mark);

}

int firstMark = markList.remove (0);

autoboxing

unboxing

Page 41: Improving structure with inheritance (Chapters 8 and 9)

41

private ArrayList<Integer> 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 thisso we don’t have to write this

Page 42: Improving structure with inheritance (Chapters 8 and 9)

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).

Page 43: Improving structure with inheritance (Chapters 8 and 9)

More about inheritance

Exploring polymorphism

(Chapter 9)

Page 44: Improving structure with inheritance (Chapters 8 and 9)

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

Page 45: Improving structure with inheritance (Chapters 8 and 9)

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

The inheritance hierarchy

Page 46: Improving structure with inheritance (Chapters 8 and 9)

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

Conflicting output

CD: A Swingin' Affair (64 mins)*CD: A Swingin' Affair (64 mins)* Frank SinatraFrank Sinatra tracks: 16tracks: 16 my favourite Sinatra albummy favourite Sinatra album  DVD: O Brother, Where Art Thou? (106 mins)DVD: O Brother, Where Art Thou? (106 mins) Joel & Ethan CoenJoel & Ethan Coen The Coen brothers’ best movieThe Coen brothers’ best movie!!

title: A Swingin' Affair (64 mins)*title: A Swingin' Affair (64 mins)* my favourite Sinatra albummy favourite Sinatra album

title: title: O Brother, Where Art Thou? (106 mins)O Brother, Where Art Thou? (106 mins) The Coen brothers’ best movieThe Coen brothers’ best movie!!

What we wantWhat we want

What we haveWhat we have

Page 47: Improving structure with inheritance (Chapters 8 and 9)

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

The problem

• The The printprint method in method in ItemItem only only prints the common fields.prints the common fields.

• Inheritance is a one-way street:Inheritance is a one-way street:– A subclass inherits the superclass A subclass inherits the superclass

fields.fields.– The superclass knows nothing about The superclass knows nothing about

its subclass’s fields.its subclass’s fields.

Page 48: Improving structure with inheritance (Chapters 8 and 9)

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.

Page 49: Improving structure with inheritance (Chapters 8 and 9)

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

Page 50: Improving structure with inheritance (Chapters 8 and 9)

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?

Page 51: Improving structure with inheritance (Chapters 8 and 9)

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 The declared type of a variable is its its static typestatic type..

• The type of the object a variable The type of the object a variable refers to is its refers to is its dynamic typedynamic type..

• The compiler’s job is to check for The compiler’s job is to check for static-typestatic-type violations. violations.

for(Item item : items) {for(Item item : items) { item.print(); item.print(); // Compile-time error.// Compile-time error.}}

Page 52: Improving structure with inheritance (Chapters 8 and 9)

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.

Page 53: Improving structure with inheritance (Chapters 8 and 9)

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?

Page 54: Improving structure with inheritance (Chapters 8 and 9)

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.

Page 55: Improving structure with inheritance (Chapters 8 and 9)

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.

Page 56: Improving structure with inheritance (Chapters 8 and 9)

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.

Page 57: Improving structure with inheritance (Chapters 8 and 9)

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.

Page 58: Improving structure with inheritance (Chapters 8 and 9)

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 ... but we often still want to be able

to call them.to call them.• An overridden method An overridden method cancan be be

called from the method that called from the method that overrides it.overrides it.– super.print (...)super.print (...)– Compare with the use of Compare with the use of supersuper in in

constructors.constructors.

Page 59: Improving structure with inheritance (Chapters 8 and 9)

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

Calling an overridden method

public class CD extends Itempublic 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); }}

......

}}

Page 60: Improving structure with inheritance (Chapters 8 and 9)

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

Method polymorphism

• We have been discussing We have been discussing polymorphic method dispatchpolymorphic method dispatch..

• A polymorphic variable can store A polymorphic variable can store objects of varying types.objects of varying types.

• Method calls are Method calls are polymorphic..– The actual method called depends The actual method called depends

on the dynamic object type.on the dynamic object type.

Page 61: Improving structure with inheritance (Chapters 8 and 9)

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

The Object class’s methods

• Methods in Methods in ObjectObject are inherited are inherited by all classes.by all classes.

• Any of these may be overridden.Any of these may be overridden.• The The toStringtoString method (of method (of ObjectObject) is commonly overridden:) is commonly overridden:– public String toString ()public String toString ()– Returns a string representation of Returns a string representation of

the object.the object.

Page 62: Improving structure with inheritance (Chapters 8 and 9)

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

Overriding toStringpublic class Itempublic 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"); }} }}

......}}

Page 63: Improving structure with inheritance (Chapters 8 and 9)

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

Overriding toString

• Explicit Explicit printprint methods can often methods can often be omitted from a class:be omitted from a class:

System.out.println (item.toString());System.out.println (item.toString());

• Calls to Calls to printlnprintln with just an with just an object automatically result in object automatically result in toStringtoString being called: being called:

System.out.println (item);System.out.println (item);

Page 64: Improving structure with inheritance (Chapters 8 and 9)

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 Private access in the superclass may be too restrictive for a subclass.too restrictive for a subclass.

• The closer inheritance relationship is The closer inheritance relationship is supported by supported by protected accessprotected access: protected : protected things (fields, constructors, methods, etc.) things (fields, constructors, methods, etc.) may be used by sub-classes.may be used by sub-classes.

• Protected access is more restricted than Protected access is more restricted than public access.public access.

• We still recommend We still recommend keeping fields keeping fields privateprivate..– Define protected accessors and mutators for Define protected accessors and mutators for

sub-classes to use.sub-classes to use.

Page 65: Improving structure with inheritance (Chapters 8 and 9)

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

Access levels

Page 66: Improving structure with inheritance (Chapters 8 and 9)

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 The declared type of a variable is its

static typestatic type::– Compilers check static types.Compilers check static types.

• The type of an object is its The type of an object is its dynamic typedynamic type::– Dynamic types are used at runtime.Dynamic types are used at runtime.

• Methods may be Methods may be overriddenoverridden in a in a subclass.subclass.

• Method lookup starts with the Method lookup starts with the dynamic dynamic typetype..

• ProtectedProtected access reflects access reflects inheritanceinheritance..


Recommended