SlideShare a Scribd company logo
1 of 42
Structure -
Inheritance
Main concepts to be
covered
Inheritance
Subtyping
Substitution
Polymorphic variables
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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.
DoME objects
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
DoME classes
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
top half
shows fields
bottom half
shows methods
DoME object model
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
Class diagram
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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!)[ ]
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!)[ ]
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
}}
}}
}}
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.
Using inheritance
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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.
Inheritance hierarchies
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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
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
}}
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
}
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
}}
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
}}
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.
Adding more item types
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
Deeper hierarchies
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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.
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!
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();
}}
}}
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););
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.
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
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
Object diagram
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
Class diagram
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
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.
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.
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.
The Object class
OBJECTS FIRST WITH JAVA - A PRACTICAL
INTRODUCTION USING BLUEJ, © DAVID J.
All classes inherit
from Object.
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.
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.
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
... ...
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.
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
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
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.

More Related Content

What's hot

What's hot (10)

Docker 入門 Introduction to Docker
Docker 入門  Introduction to DockerDocker 入門  Introduction to Docker
Docker 入門 Introduction to Docker
 
Sls01 Lecture02 Linux In Practice
Sls01 Lecture02 Linux In PracticeSls01 Lecture02 Linux In Practice
Sls01 Lecture02 Linux In Practice
 
Linux Containers (LXC)
Linux Containers (LXC)Linux Containers (LXC)
Linux Containers (LXC)
 
Linux class 9 15 oct 2021-5
Linux class 9   15 oct 2021-5Linux class 9   15 oct 2021-5
Linux class 9 15 oct 2021-5
 
Linux class 10 15 oct 2021-6
Linux class 10   15 oct 2021-6Linux class 10   15 oct 2021-6
Linux class 10 15 oct 2021-6
 
Odata consuming-services-slides
Odata consuming-services-slidesOdata consuming-services-slides
Odata consuming-services-slides
 
Lecture6
Lecture6Lecture6
Lecture6
 
Python lec4
Python lec4Python lec4
Python lec4
 
ikh331-06-distributed-programming
ikh331-06-distributed-programmingikh331-06-distributed-programming
ikh331-06-distributed-programming
 
NIO.2, the I/O API for the future
NIO.2, the I/O API for the futureNIO.2, the I/O API for the future
NIO.2, the I/O API for the future
 

Similar to Improving structure

Connect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaConnect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaJulian Robichaux
 
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...panagenda
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?ColdFusionConference
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
MyTunesbuild.xml Builds, tests, and runs the project M.docx
MyTunesbuild.xml      Builds, tests, and runs the project M.docxMyTunesbuild.xml      Builds, tests, and runs the project M.docx
MyTunesbuild.xml Builds, tests, and runs the project M.docxgilpinleeanna
 
Anatomy of a Gradle plugin
Anatomy of a Gradle pluginAnatomy of a Gradle plugin
Anatomy of a Gradle pluginDmytro Zaitsev
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know Norberto Leite
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)MongoDB
 
Idiomatic gradle plugin writing
Idiomatic gradle plugin writingIdiomatic gradle plugin writing
Idiomatic gradle plugin writingSchalk Cronjé
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartGabriele Lana
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingSchalk Cronjé
 
Improving code quality with loose coupling
Improving code quality with loose couplingImproving code quality with loose coupling
Improving code quality with loose couplingNemanja Ljubinković
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Tino Isnich
 
Question- Write the Java code below in IDE ECLIPSE enviroment and prov.docx
Question- Write the Java code below in IDE ECLIPSE enviroment and prov.docxQuestion- Write the Java code below in IDE ECLIPSE enviroment and prov.docx
Question- Write the Java code below in IDE ECLIPSE enviroment and prov.docxHarryXQjCampbellz
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerGarth Gilmour
 
Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?devObjective
 

Similar to Improving structure (20)

Chapter08
Chapter08Chapter08
Chapter08
 
Connect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaConnect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and Java
 
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
 
Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?Dependency Injection Why is it awesome and Why should I care?
Dependency Injection Why is it awesome and Why should I care?
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Annotation processing tool
Annotation processing toolAnnotation processing tool
Annotation processing tool
 
MyTunesbuild.xml Builds, tests, and runs the project M.docx
MyTunesbuild.xml      Builds, tests, and runs the project M.docxMyTunesbuild.xml      Builds, tests, and runs the project M.docx
MyTunesbuild.xml Builds, tests, and runs the project M.docx
 
Anatomy of a Gradle plugin
Anatomy of a Gradle pluginAnatomy of a Gradle plugin
Anatomy of a Gradle plugin
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 
Idiomatic gradle plugin writing
Idiomatic gradle plugin writingIdiomatic gradle plugin writing
Idiomatic gradle plugin writing
 
Refactoring In Tdd The Missing Part
Refactoring In Tdd The Missing PartRefactoring In Tdd The Missing Part
Refactoring In Tdd The Missing Part
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Idiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin WritingIdiomatic Gradle Plugin Writing
Idiomatic Gradle Plugin Writing
 
Improving code quality with loose coupling
Improving code quality with loose couplingImproving code quality with loose coupling
Improving code quality with loose coupling
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
Question- Write the Java code below in IDE ECLIPSE enviroment and prov.docx
Question- Write the Java code below in IDE ECLIPSE enviroment and prov.docxQuestion- Write the Java code below in IDE ECLIPSE enviroment and prov.docx
Question- Write the Java code below in IDE ECLIPSE enviroment and prov.docx
 
Lies Told By The Kotlin Compiler
Lies Told By The Kotlin CompilerLies Told By The Kotlin Compiler
Lies Told By The Kotlin Compiler
 
Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?Dependency Injection: Why is awesome and why should I care?
Dependency Injection: Why is awesome and why should I care?
 

More from Fajar Baskoro

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxFajar Baskoro
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterFajar Baskoro
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanFajar Baskoro
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUSFajar Baskoro
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxFajar Baskoro
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdfFajar Baskoro
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptxFajar Baskoro
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptxFajar Baskoro
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxFajar Baskoro
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimFajar Baskoro
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahFajar Baskoro
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaFajar Baskoro
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetFajar Baskoro
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdfFajar Baskoro
 

More from Fajar Baskoro (20)

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptx
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarter
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUS
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptx
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptx
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptx
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi Kaltim
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolah
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remaja
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
 
epl1.pdf
epl1.pdfepl1.pdf
epl1.pdf
 
user.docx
user.docxuser.docx
user.docx
 
Dtmart.pptx
Dtmart.pptxDtmart.pptx
Dtmart.pptx
 
DualTrack-2023.pptx
DualTrack-2023.pptxDualTrack-2023.pptx
DualTrack-2023.pptx
 
BADGE.pptx
BADGE.pptxBADGE.pptx
BADGE.pptx
 
womenatwork.pdf
womenatwork.pdfwomenatwork.pdf
womenatwork.pdf
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdf
 

Recently uploaded

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Hararemasabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benonimasabamasaba
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2
 

Recently uploaded (20)

W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 

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.
  • 4. DoME objects 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
  • 6. DoME object model OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J.
  • 7. Class diagram OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J.
  • 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.
  • 12. Using inheritance 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.
  • 14. Inheritance hierarchies 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.
  • 22. Deeper hierarchies 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
  • 30. Object diagram OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J.
  • 31. Class diagram OBJECTS FIRST WITH JAVA - A PRACTICAL INTRODUCTION USING BLUEJ, © DAVID J.
  • 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

  1. database to store details of all CDs and videos I know
  2. one object per CD or video; each object stores details for one item.
  3. add the obvious methods (getters and setters); not complete here - just examples add a print method to print out the details
  4. database object will hold two collections: one for CDs, one for videos
  5. class diagram is simple (ArrayList not shown in BlueJ)
  6. extract from CD code - nothing unusual
  7. extract from video code (how does it differ from CD code?)
  8. extract from database code.
  9. we note a lot of code duplication. this is one problem with this solution (there are others)
  10. solution: inheritance. make superclass with common attributes, make subclasses
  11. inheritance hierarchies are nothing unusual. we see them all the time. (a masters student is a students is a person...)
  12. syntax for inheritance: extends keyword
  13. we define common fields in superclass
  14. we add subclass fields; inherit superclass fields (note extends keyword) subclass objects will have all fields.
  15. how do we initialise the fields? superclass: nothing unusual.
  16. subclass: must call superclass constructor! Must take values for all fields that we want to initialise.
  17. it is now much easier to add new types. common attributes do not need to be rewritten.
  18. when adding new types, the hierarchy may be extended
  19. note: code duplication in class Database removed as well! only on field, one ArrayList creation, on add method
  20. ...and only one loop in list method.
  21. database object will hold two collections: one for CDs, one for videos
  22. class diagram is simple (ArrayList not shown in BlueJ)