242-210 Programming Fundamentals 2: Inheritance/7 1 242-210 F II Objectives – –to introduce inheritance, superclasses, subclasses, polymorphic data structures,

Slides:



Advertisements
Similar presentations
FEN IntroJava2006 AAU1 Nedarvning Specialisering/Generalisering Subklasse/Superklasse Statisk/Dynamisk type Polymorfi Interfaces.
Advertisements

1 Value vs. reference semantics. Recall: Value semantics value semantics: Behavior where variables are copied when assigned to each other or passed as.
OOP (Java): Inheritance/ OOP Objectives – –to introduce inheritance, superclasses, subclasses, polymorphic data structures, and wrapper.
Inheritance in collections Week Main concepts to be covered Inheritance in ArrayList objects Subtyping Substitution.
CS1054: Lecture 18 - Inheritance. The DoME example "Database of Multimedia Entertainment" stores details about CDs and videos –CD: title, artist, # tracks,
Objects First With Java A Practical Introduction Using BlueJ Improving structure with inheritance 2.0.
Improving structure with inheritance Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts.
1 OOP in C#:Object Interaction. Inheritance and Polymorphism. Session 2: OOP in C#
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Improving structure with inheritance (Chapters 8 and 9)
Improving structure with inheritance
Improving structure with inheritance. 25/11/2004Lecture 7: Inheritance2 Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Using Collections. Review of Collections Using an ArrayList It increases its capacity as necessary. It keeps a private count ( size() accessor). It keeps.
Inheritance Chapter 8.
More about inheritance Exploring polymorphism. 02/12/2004Lecture 8: More about inheritance2 Main concepts to be covered method polymorphism static and.
CPSC150 Inheritance Details Chapter 9. CPSC150 Print in Entertainment ver 2 (with inheritance): public void print() { System.out.print("title: " + title.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
CPSC150 Interfaces Chapter CPSC150 Inheritance Review No different than any other class. Has no access to or information about subclasses class.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Abstract Classes and Interfaces
More about inheritance Exploring polymorphism 3.0.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
1 Exercise /* A lockbox can be open or closed. If closed, only a valid password will open the box. Once the box is open, the contents can be retrieved.
Programming Fundamentals 2: Inheritance/ F II Objectives – –the use of super, overriding, method polymorphism (dynamic binding), protected.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
CS305j Introduction to Computing Inheritance and Polymorphism 1 Topic 26 Introduction to Inheritance and Polymorphism "One purpose of CRC cards [a design.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance.
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
ArrayList, Multidimensional Arrays
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables Objects First with Java.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Objects First With Java A Practical Introduction Using BlueJ Method overriding 2.0.
Comp1004: Inheritance I Super and Sub-classes. Coming up Inheritance and Code Duplication – Super and sub-classes – Inheritance hierarchies Inheritance.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Composition When one class contains an instance variable whose type is another class, this is called composition. Instead of inheritance, which is based.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
Improving structure with inheritance 3.0. The media project stores details about CDs and DVDs –CD: title, artist, number of tracks, playing time, got-it,
Session 06: C# OOP-3 Inheritance and Polymorphism. Static and dynamic type of an object. FEN AK - IT: Softwarekonstruktion.
CS 112 Programming 2 Lecture 06 Inheritance & Polymorphism (1)
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
OOP Basics Classes & Methods (c) IDMS/SQL News
1 COS 260 DAY 17 Tony Gauvin. 2 Agenda Questions? 7 th Mini quiz –Chapter 7 –Password “GoBengals” –40 min Assignment 4 posted –Due Nov 9 (one week) Capstone.
1 COS 260 DAY 18 Tony Gauvin. 2 Agenda Questions? 7 th Mini quiz Graded –Good results 8 th Mini Quiz –Chap 8  Next class Assignment 4 Due Assignment.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Improving structure with inheritance Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables © 2017 Pearson Education,
Coming up Inheritance – Code duplication – Super classes – Constructors Polymorphic collections – “Anywhere a super class is, a sub class can go” Casting.
CMSC 202 ArrayList Aug 9, 2007.
9 Improving structure with inheritance
Sixth Lecture ArrayList Abstract Class and Interface
More about inheritance
Lecture 19 - Inheritance (Contd).
More about inheritance
CMSC 202 ArrayList Aug 9, 2007.
COS 260 DAY 18 Tony Gauvin.
CMSC 202 ArrayList Aug 9, 2007.
F II 3. Classes and Objects Objectives
Objects First with Java
Comp1202: Inheritance I Super and Sub-classes.
F II 8. More on Inheritance Objectives
Improving structure with inheritance
Lecture 15 Inheritance.
Presentation transcript:

Programming Fundamentals 2: Inheritance/ F II Objectives – –to introduce inheritance, superclasses, subclasses, polymorphic data structures, and wrapper classes Semester 2, Inheritance Original Slides by Dr. Andrew Davison

Programming Fundamentals 2: Inheritance/7 2 Topics 1. The DoME Example 2. Inheritance Hierarchies 3. DoME using Inheritance 4. Polymorphism 5. The Revised Database Class 6. Classes and Types 7. A Vehicle Example 8. The Object Class 9. Collections and Primitive Types

Programming Fundamentals 2: Inheritance/ The DoME Example DoME = "Database of Multimedia Entertainment" The database stores details about CDs and DVDs in ArrayLists – –CD: title, artist, no. of tracks, playing time, a got-it, flag, a comment – –DVD: title, director, playing time, got-it, comment The details can be printed.

Programming Fundamentals 2: Inheritance/7 4 DoME Classes essModel cannot display the ArrayLists properly "uses"

Programming Fundamentals 2: Inheritance/7 5 DoME Objects

Programming Fundamentals 2: Inheritance/7 6 The CD Class public class CD { private String title, artist, comment; private int numberOfTracks, playingTime; private boolean gotIt; public CD(String theTitle, String theArtist, int tracks, int time) { title = theTitle; artist = theArtist; numberOfTracks = tracks; playingTime = time; gotIt = false; comment = null; } // end of CD() continued

Programming Fundamentals 2: Inheritance/7 7 public void setComment(String com) { comment = com; } public String getComment() { return comment; } public void setOwn(boolean ownIt) // set the flag indicating whether we own this CD. { gotIt = ownIt; } public boolean getOwn() // return true if we own a copy of this CD. { return gotIt; } continued

Programming Fundamentals 2: Inheritance/7 8 public void print() // print details about this CD { System.out.print("CD: " + title + " (" + playingTime + " mins)"); if (gotIt) System.out.println("*"); else System.out.println(); System.out.println(" " + artist); System.out.println(" tracks: " + numberOfTracks); if (comment != null) System.out.println(" " + comment); } // end of print() } // end of CD class

Programming Fundamentals 2: Inheritance/7 9 The DVD Class public class DVD { private String title, director, comment; private int playingTime; // playing time of the movie private boolean gotIt; public DVD(String theTitle, String theDirector, int time) { title = theTitle; director = theDirector; playingTime = time; gotIt = false; comment = null; } // end of DVD() Notice the many similarities with the CD class. continued

Programming Fundamentals 2: Inheritance/7 10 public void setComment(String com) { comment = com; } public String getComment() { return comment; } public void setOwn(boolean ownIt) // set the flag indicating whether we own this DVD. { gotIt = ownIt; } public boolean getOwn() // return true if we own a copy of this DVD. { return gotIt; } continued

Programming Fundamentals 2: Inheritance/7 11 public void print() // print details about this DVD { System.out.print("DVD: " + title + " (" + playingTime + " mins)"); if (gotIt) System.out.println("*"); else System.out.println(); System.out.println(" " + director); if (comment != null) System.out.println(" " + comment); } // end of print() } // end of DVD class

Programming Fundamentals 2: Inheritance/7 12 The Database Class public class Database { private ArrayList cds; private ArrayList dvds; public Database() { cds = new ArrayList (); dvds = new ArrayList (); } public void addCD(CD theCD) { cds.add(theCD); } public void addDVD(DVD theDVD) { dvds.add(theDVD); } Notice the code duplication due to the use of two ArrayLists. continued

Programming Fundamentals 2: Inheritance/7 13 public void list() // print a list of all currently stored CDs and DVDs { for (CD cd : cds) cd.print(); for (DVD dvd : dvds) dvd.print(); } // end of list() } // end of Database class

Programming Fundamentals 2: Inheritance/7 14 Using the DoME Database public class UseDome1 { public static void main(String[] args) { Database db = new Database(); CD beatles = new CD("the white album", "the beatles",13, 122); db.addCD( beatles); beatles.setComment("the best of the later period"); db.addCD( new CD("morrison hotel", "the doors", 11, 109)); db.addCD( new CD("dark side of the moon","pink floyd",9,100)); : continued

Programming Fundamentals 2: Inheritance/7 15 db.addDVD( new DVD("citizen kane", "welles", 97)); DVD drs = new DVD("dr. strangelove", "kubrick", 143); drs.setComment("what was written on the bomb?"); db.addDVD(drs); db.addDVD( new DVD("star wars: a new hope", "lucas", 100)); db.list(); } // end of UseDome1() } // end of UseDome1 class

Programming Fundamentals 2: Inheritance/7 16 Execution

Programming Fundamentals 2: Inheritance/7 17 Problems with DoME's Design Code duplication: the CD and DVD classes are very similar – –it makes maintenance harder – –it introduces the danger of bugs The Database class also suffers from code duplication.

Programming Fundamentals 2: Inheritance/ Inheritance Hierarchies "is a"

Programming Fundamentals 2: Inheritance/ DoME using Inheritance "is a" Compare the fields and methods with those for CD and DVD in slide 4.

Programming Fundamentals 2: Inheritance/7 20 Inheritance Terminlogy The Item class is a superclass. The new versons of the CD and DVD classes are subclasses – –the superclass defines fields (attributes) and methods which are inherited by the subclasses – –the subclasses add extra fields and methods

Programming Fundamentals 2: Inheritance/7 21 The Item Class public class Item { private String title, comment; private int playingTime; private boolean gotIt; public Item(String theTitle, int time) { title = theTitle; playingTime = time; gotIt = false; comment = null; } continued Fields and methods that were common to the old CD and DVD classes are now in the Item superclass.

Programming Fundamentals 2: Inheritance/7 22 public void setComment(String com) { comment = com; } public String getComment() { return comment; } public void setOwn(boolean ownIt) // set the flag indicating whether we own this item. { gotIt = ownIt; } public boolean getOwn() // return true if we own a copy of this item. { return gotIt; } continued

Programming Fundamentals 2: Inheritance/7 23 public void print() // print details about this item { System.out.print("title: " + title + " (" + playingTime + " mins)"); if (gotIt) System.out.println("*"); else System.out.println(); if (comment != null) System.out.println(" " + comment); } // end of print() } // end of Item class

Programming Fundamentals 2: Inheritance/7 24 The Revised CD Class public class CD extends Item { private String artist; private int numTracks; public CD(String theTitle, String theArtist, int tracks, int time) { super(theTitle, time); artist = theArtist; numTracks = tracks; } public String getArtist() { return artist; } public int getNumberOfTracks() { return numTracks; } } // end of CD class Much shorter than the old CD class.

Programming Fundamentals 2: Inheritance/7 25 How is this Line Now Executed? CD beatles = new CD("the white album", "the beatles",13, 122);

Programming Fundamentals 2: Inheritance/7 26 The Revised DVD Class public class DVD extends Item { private String director; public DVD(String theTitle, String theDirector, int time) { super(theTitle, time); director = theDirector; } public String getDirector() { return director; } } // end of DVD class Much shorter than the old DVD class.

Programming Fundamentals 2: Inheritance/7 27 How is this Line Executed? DVD d1 = new DVD("citizen kane", "welles", 97)

Programming Fundamentals 2: Inheritance/7 28 Superclass Constructor Call The subclass constructors should always contain a super() call as the first statement. CD has 6 fields (4 inherited) and 9 methods (6 inherited) DVD has 5 fields (4 inherited) and 8 methods (6 inherited),

Programming Fundamentals 2: Inheritance/7 29 Adding More Item Subclasses continued "is a"

Programming Fundamentals 2: Inheritance/7 30 "is a"

Programming Fundamentals 2: Inheritance/7 31 The Benefits of Inheritance A comparison between the old and new versions of CD and DVD show: – –no code duplication – –code reuse (of Item) Inheritance simplifies: – –maintenance, extendibility

Programming Fundamentals 2: Inheritance/ Polymorphism A superclass variable can be assigned any subclass object: A superclass variable can be assigned any subclass object: Item a1 = new CD(...); Item a2 = new DVD(...); "is a" continued

Programming Fundamentals 2: Inheritance/7 33 This polymorphic feature becomes very useful when a collection (e.g. ArrayList, array, HashMap) is defined using a superclass This polymorphic feature becomes very useful when a collection (e.g. ArrayList, array, HashMap) is defined using a superclass –the collection can store subclass objects

Programming Fundamentals 2: Inheritance/7 34 Polymorphic Data Structures Normal data structures (e.g. int a[] ) can only hold one type of thing (e.g integers). Normal data structures (e.g. int a[] ) can only hold one type of thing (e.g integers). A polymorphic data structure can hold different types of objects A polymorphic data structure can hold different types of objects –the trick is to define the data structure using a superclass (e.g. Item) –it can then hold subclass objects (e.g. CD, DVD)

Programming Fundamentals 2: Inheritance/7 35 Items ArrayList : ArrayList items = new ArrayList ; items.add( new CD(...) ); items.add( new DVD(...) ); items.add( new CD(...) ); items.add( new DVD(...) ); :.. items any subclass objects of Item

Programming Fundamentals 2: Inheritance/ The Revised Database Class import java.util.ArrayList; public class Database { private ArrayList items; public Database() { items = new ArrayList (); } public void addItem(Item theItem) { items.add(theItem); } Only one ArrayList, and only Item objects are being manipulated. continued

Programming Fundamentals 2: Inheritance/7 37 public void list() // print a list of all currently stored items { for (Item item : items) item.print(); } // end of list() } // end of Database class No code duplication unlike in the old version of Database.

Programming Fundamentals 2: Inheritance/7 38 Class Diagram "is a" "uses" o o Why does Database now use Item instead of CD and DVD? o o Because Item is a superclass of CD and DVD, which allows Database to manipulate objects of both subclasses.

Programming Fundamentals 2: Inheritance/7 39 Changes from the Old Database Now there is only one ArrayList, which stores Item objects Now there is only one ArrayList, which stores Item objects –called a polymorphic data structure The use of a single ArrayList simplifies the Database methods The use of a single ArrayList simplifies the Database methods –no more code duplication due to the use of two ArrayLists for CDs and DVDs

Programming Fundamentals 2: Inheritance/7 40 A Polymorphic Interface The items polymorphic data structure in Database is accessed using methods that take a superclass parameter (i.e. Item) The items polymorphic data structure in Database is accessed using methods that take a superclass parameter (i.e. Item) This means that the methods can accept arguments which are subclass objects (i.e. CD and DVD objects) This means that the methods can accept arguments which are subclass objects (i.e. CD and DVD objects)

Programming Fundamentals 2: Inheritance/7 41 Superclass Parameters In the first Database class: public void addCD(CD theCD); public void addVideo( DVD the DVD ); Now, Database has: public void addItem(Item theItem) This method is called with: DVD myDVD = new DVD(...); database.addItem(myDVD);CD myCD = new CD(...);database.addItem(myCD); A subclass object can be passed to the Item superclass parameter of addItem().

Programming Fundamentals 2: Inheritance/7 42 Using DoME (v.2) public class UseDome2 { public static void main(String[] args) { Database db = new Database(); CD beatles = new CD("the white album", "the beatles",13,122); db.addItem(beatles); beatles.setComment("the best of the later period"); db.addItem(new CD("morrison hotel", "the doors", 11, 109)); db.addItem(new CD("dark side of the moon","pink floyd",9,100)); : continued

Programming Fundamentals 2: Inheritance/7 43 db.addItem(new DVD("citizen kane", "welles", 97)); DVD drs = new DVD("dr. strangelove", "kubrick", 143); drs.setComment("what was written on the bomb?"); db.addItem(drs); db.addItem(new DVD("star wars: a new hope", "lucas", 100)); db.list(); } // end of UseDome2() } // end of UseDome2 class

Programming Fundamentals 2: Inheritance/7 44 Object Diagram Compare with the old version of Database shown in slide 5.

Programming Fundamentals 2: Inheritance/7 45 Execution There's a 'problem' with this output, which I'll discuss (and fix) in Part 9. Compare with slide 16

Programming Fundamentals 2: Inheritance/ Classes and Types Sometimes classes can be thought of as new types: – –superclasses are supertypes – –subclasses are subtypes Subclass (subtype) objects can be assigned to superclass (supertype) variables.

Programming Fundamentals 2: Inheritance/ A Vehicle Example Vehicle is a superclass, with subclasses for different types of vehicles. Vehicle is a superclass, with subclasses for different types of vehicles. "is a" wheels, seats a bell an engine

Programming Fundamentals 2: Inheritance/7 48 A Vehicle Array : Vehicle vs[] = new Vehicle[100]; vs[0] = new Bicycle(...); vs[1] = new Car(...); vs[2] = new Bicycle(...); vs[3] = new Car(...); :.. vs any subclass object of Vehicle This time the polymorphic data structure is an array.

Programming Fundamentals 2: Inheritance/7 49 One-way Casting We can assign subclass objects to superclass variables: Vehicle v = new Bicycle(...); // ok Ok since a bicycle has all the features of a vehicle, and some extra ones (e.g. a bell) which do not matter. continued

Programming Fundamentals 2: Inheritance/7 50 In general, we cannot assign superclass objects to subclass variables: Bicycle b = new Vehicle(...); // compile-time error An error since a vehicle does not have all the features of a bicycle (e.g. no bell).

Programming Fundamentals 2: Inheritance/ The Object Class All classes are subclasses of the Object class All classes are subclasses of the Object class –Object is a sort of "super-grandfather" of every class All classes inherit from Object. "is a" continued

Programming Fundamentals 2: Inheritance/7 52 This means that a collection (ArrayList, array, etc) of type Object can store any kind of object: This means that a collection (ArrayList, array, etc) of type Object can store any kind of object: ArrayList list = new ArrayList (); list.add( "andrew" ); list.add( new CD(...) ); list.add( new Bike(...) );

Programming Fundamentals 2: Inheritance/ Collections and Primitive Types Objects can be added to a collection. But what about variables of primitive types, (which are not objects)? – –e.g. int x; float f; char ch;

Programming Fundamentals 2: Inheritance/7 54 Wrapper Classes Primitive types (int, char, etc) are not classes. – –a primitive variable must be wrapped up as an object Wrapper classes exist for all primitive types: Primitive typeWrapper class intInteger floatFloat charCharacter...

Programming Fundamentals 2: Inheritance/7 55 Using Wrapper Classes ArrayList markList = new ArrayList (); int mk = 72; Integer iwrap = new Integer(mk); markList.add(iwrap);... Integer iObj = markList.get(0); int value = iObj.intValue(); wrap var (int --> Integer) unwrap it (Integer --> int) In practice, autoboxing and unboxing mean we don't often have to do this.

Programming Fundamentals 2: Inheritance/7 56 Autoboxing and Unboxing ArrayList markList = new ArrayList (); int mk = 72; markList.add(mk);... int value = markList.get(0); autoboxing: int --> Integer unboxing: Integer --> int