More Related Content
Similar to Improving structure
Similar to Improving structure (20)
More from Fajar Baskoro (20)
Improving structure
- 2. Main concepts to be
covered
Inheritance
Subtyping
Substitution
Polymorphic variables
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 3. 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
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 5. DoME classes
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
top half
shows fields
bottom half
shows methods
- 8. CD
source
code
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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 theArtist)public CD (String theTitle, String 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!)[ ]
- 9. DVD
source
code
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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 theDirector)public DVD (String theTitle, String 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!)[ ]
- 10. Database source code
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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
}}
}}
}}
- 11. 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
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 13. 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
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 15. Inheritance in Java
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
public class Itempublic class Item
{{
......
}}
public class CD extends Itempublic class CD extends Item
{{
......
}}
public classpublic class DVDDVD extends Itemextends Item
{{
......
}}
no change here
change here
- 16. Superclass
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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
}}
- 17. Subclasses
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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. Inheritance and
constructors
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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
}}
- 19. Inheritance and
constructors
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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;
}}
...... methodsmethods
}}
- 20. Superclass constructor call
•Subclass constructors must always contain a 'Subclass constructors must always contain a 'supersuper' call.' 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 parametersthis works only, if the superclass has a constructor without parameters
•The 'The 'supersuper' call must be the first statement in the subclass constructor.' call must be the first statement in the subclass constructor.
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 21. Adding more item types
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 23. Review (so far)
Inheritance (so far) helps with:
Avoiding code duplication
Code reuse
Easier maintenance
Extendibility
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 24. New
Database
source
code
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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);
}}
...... listlist
}}
avoids code
duplication in
client!
- 25. New Database source
code
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
/**/**
* 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();
}}
}}
- 26. Subtyping
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
First, we had:First, we had:
public void addCDpublic void addCD (CD theCD)(CD theCD)
public void addVideopublic void addVideo ((DVDDVD thetheDVDDVD))
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 mymyDVDDVD = new= new DVDDVD (...);(...);
database.addItemdatabase.addItem (my(myDVDDVD););
- 27. 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 areObjects of subclasses can be used where objects of supertypes are
required.required.
(This is called(This is called substitutionsubstitution.).)
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 28. Subtyping and assignment
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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 objectssubclass objects
may be assignedmay be assigned
to superclassto superclass
variablesvariables
- 29. Subtyping and parameter
passing
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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 objectssubclass objects
may be passed tomay be passed to
superclasssuperclass
parametersparameters
- 32. 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.
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 33. 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 ais not a CarCar!)!)
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 34. 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:
◦ ClassCastExceptionClassCastException if it isn't!if it isn't!
Use it sparingly.Use it sparingly.
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 35. The Object class
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
All classes inherit
from Object.
- 36. Polymorphic collections
All collections are polymorphic.All collections are polymorphic.
We can have collections ofWe 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)
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 37. 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... because such collections accept elements of type ObjectObject......
•... and all classes are subtypes of... and all classes are subtypes of ObjectObject..
•Great! But what about simple types?Great! But what about simple types?
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
- 38. 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:
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
simple type wrapper class
int Integer
float Float
char Character
... ...
- 39. Wrapper classes
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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.
- 40. Autoboxing and unboxing
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
private ArrayList<Integer> markList;
…
public void storeMark (int mark)
{
markList.add (mark);
}
int firstMark = markList.remove (0);
autoboxing
unboxing
- 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
- 42. 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).
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
Editor's Notes
- database to store details of all CDs and videos I know
- one object per CD or video; each object stores details for one item.
- add the obvious methods (getters and setters); not complete here - just examples
add a print method to print out the details
- database object will hold two collections: one for CDs, one for videos
- class diagram is simple (ArrayList not shown in BlueJ)
- extract from CD code - nothing unusual
- extract from video code (how does it differ from CD code?)
- extract from database code.
- we note a lot of code duplication.
this is one problem with this solution (there are others)
- solution: inheritance. make superclass with common attributes, make subclasses
- inheritance hierarchies are nothing unusual. we see them all the time.
(a masters student is a students is a person...)
- syntax for inheritance: extends keyword
- we define common fields in superclass
- we add subclass fields; inherit superclass fields (note extends keyword)
subclass objects will have all fields.
- how do we initialise the fields? superclass: nothing unusual.
- subclass: must call superclass constructor! Must take values for all
fields that we want to initialise.
- it is now much easier to add new types.
common attributes do not need to be rewritten.
- when adding new types, the hierarchy may be extended
- note: code duplication in class Database removed as well!
only on field, one ArrayList creation, on add method
- ...and only one loop in list method.
- database object will hold two collections: one for CDs, one for videos
- class diagram is simple (ArrayList not shown in BlueJ)