Title: Week 06 b
1Week 06 - b
- Vector Example
- Class Hierarchies, Inheritance
- Polymorphism
- Review for Test 2
2Sample Programs Referenced(code located in
course folder)
- VectorRace
- java inherit.InheritLab
- Monsters Inc.
- Monsters Inc. - Array
3Example Race Redo
- Remember the Race problem?
- Registration process
- Get names, assign numbers
- Record race results
- Get numbers and times as racers cross line
- Report results display names and times
- Project was done with array of Runner objects
- Array runners used to store individual runner
objects - Needed to know the maximum of runners
- Needed to keep track of the actual number of
runners - Referencing the individual objects is easy
- Index in brackets
4Example Race Redo
- Review the revised project done with Vector of
runners - Vector runners used to store individual runner
objects - No maximum size vector grows as needed
- The size of the vector the number of runners
- Referencing individual objects is harder
- Method calls
- Casting
- Run in BlueJ
5Inheritance
6Inheritance
- What is Inheritance?
- What does RX-15 mean?
- If we knew that RX-15 belonged to the bicycle
class, we would have a pretty good idea - If we further knew that it belonged to the racing
bike sub-class, we would have even more
information - The subclass RacingBike "inherits" both data
values and methods from the class Bicycle - Instance variables currentSpeed, color
- Instantiated method changePedalingSpeed
7Hierarchy of the Bicycle Class
Bicycle
MountainBike
RacingBike
TandemBike
- numWheels might be a final static variable in
Bicycle (2) - numGears might be an instance variable in Bicycle
- MountainBike, RacingBike, and TandemBike
subclasses inherit these fields as well as
methods from Bicycle. They may contain additional
fields and methods as well.
8Inheritance(Animated Illustrations)
9Hierarchies
Things
Living Things
Non-living Things
Animals
Plants
?
?
?
?
Invertebrates
Vertebrates
10Why Inheritance?
Superclass Data fields Methods
- If we need a class that is similar to another
class, we could copy the class and change it - --- OR ---
- We could EXTEND the class by creating a subclass
- The subclass can have additional data fields and
methods - The subclass inherits the data fields and methods
of the superclass
Subclass1 Data fields Methods
Subclass2 Data fields Methods
11Relationships
- "Has A" (not inheritance)
- One class has an object of another class as an
instance variable - Examples
- The Race class had a vector of objects of the
Runner class - A Car class has a gas tank which was an object of
the Tank class - "Is A" (inheritance)
- One class is a subclass of another class
12Using 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 their own attributes
13Inheritance in Java
no change here
public class Item ...
change here
public class Video extends Item ...
public class CD extends Item ...
14Adding more item types
15Superclass
public class Item private String title
private int playingTime private boolean
gotIt private String comment //
constructors and methods omitted.
16Subclasses
public class CD extends Item private String
artist private int numberOfTracks //
constructors and methods omitted.
public class Video extends Item private
String director // constructors and methods
omitted.
17Superclass Constructor
public class Item private String title
private int playingTime private boolean
gotIt private String comment /
Initialize the fields of the item. /
public Item(String theTitle, int time)
title theTitle playingTime time
gotIt false comment ""
// methods omitted
18Superclass constructor call
- Subclass constructors must always contain a
'super' call. - If none is written, the compiler inserts one
(without parameters) - works only if the superclass has a constructor
without parameters - Must be the first statement in the subclass
constructor.
19Subclass Constructor
public class CD extends Item private String
artist private int numberOfTracks /
Constructor for objects of class CD
/ public CD(String theTitle, String
theArtist, int tracks, int time)
super(theTitle, time) artist
theArtist numberOfTracks tracks
// methods omitted
20Deeper hierarchies
21Refinement vs. Replacement
- A constructor method refines the constructor of
the super class - Any new or hidden fields in the subclass are
defined by the subclass constructor, "global"
values are established by the super class - Regular methods replace super class methods with
the same "signature"
22Subclasses Superclasses
- A subclass extends another class
- A subclass inherits non-private fields (data) and
methods (behavior) from all of its ancestors - If a variable, say xyz, is defined within a
subclass with same name as one in direct
ancestor, the new definition is said to hide the
definition in the super class - If we still want to be able to refer to both
variables, we can reference super.xyz
23Hiding Member Variables
- class Suppper
- double aNumber
- . . .
-
- class Subbie extends Suppper
- int aNumber
- . . .
- aNumber (int)super.aNumber
-
- Recall issues of Scope
24Super-Duper Class
- All classes are eventually derived from Object
- As such, they should support standard Object
methods - toString()
- Printable version of data structure
- equals(obj)
- See if contents are equal as opposed to references
25The Object class
All classes inherit from Object.
26"Object" Methods
- Methods in Object are inherited by all classes.
- Any of these may be overridden.
- The toString method is most commonly overridden
- public String toString()
- Returns a string representation of the object.
27Overriding toString
public class Item ... Â public String
toString() String line1 title
" (" playingTime " mins)")
if (gotIt) return line1 " "
comment) else return line1 " "
comment) // end of toString for Item
...
28Overriding Applet Methods
- The init and paint methods are pre-defined in the
built-in class Applet, we override these methods
when we define an Applet - public class InputOutputApplet extends Applet
- public void init()
- yadda yadda
- // end of init method
- public void paint(Graphics g)
- moreYadda
- // end of paint method
- // end of InputOutputApplet class
- BTW, the built-in init and paint don't do anything
29Overriding vs Overloading
- A method is overloaded if it has multiple
definitions that are distinguished from one
another by having different numbers or types of
arguments - A method is overridden when a subclass gives a
different definition of the method with the same
number and types of arguments
30Inheritance Summary
- Inheritance helps with
- Avoiding code duplication
- Code reuse
- Easier maintenance
- Extendibility
31to the Computers
- Demo (or get help with) HW
32Java BREAK
33Monsters, Inc.
- Develop an inheritance hierarchy for monsters
- Each subclass should be more specialized than its
superclass - Design a Monster superclass
- All monsters should have ?
- All monsters should be able to do ?
34Monster ProjectBlueJ
- Review the Monsters Inc project in BlueJ
- Review the Monster super class
- Instance variables
- Constructor
- Methods (including toString)
- Review the MonsterApp and MonsterMixer classes
- What is the relationship between a MonsterMixer
and a Monster? (is a or has a)
35Implementing SubClasses
- A subclass extends its superclass
- Heading for a subclass
- public class className extends superclassName
- Where have we seen this?
- Subclasses may have additional data fields and
methods - Design a subclass of Monster
- Data fields Do we need to repeat those in
Monster? - Methods Do we need to repeat those in Monster?
- What about toString? Do we write another from
scratch? - Constructor Do we need to assign all the
instance variables or can we call the constructor
from Monster?
36Inheritance and Constructors
- Can call the constructor of the super class
- Must be the first statement in the constructor
- Syntax
- super( arguments )
- Can also call other methods of the super class by
using the keyword super - Example
- super.toString()
37Overriding
- All monsters can move, but do they move in the
same way? - Can a subclass have its own move method?
- If so, which method would be called?
- Method overriding
- A method defined in a subclass blocks the
execution of a method with the same signature in
its superclass - View new move methods for some subclasses
- Test in the mixer
38Overloadingreview
- We have written classes that have multiple
constructors - Default constructor with no parameters
- Another constructor with parameters for the
instance variables - Why does this work?
- Overloading allows us to write multiple methods
in a class with the same name. - Each method must have a unique signature.
- The signature consists of the method name and the
parameter list. - Review second scare method in the Monster class
- integer parameter specifies the number of times
to write the scare message. - Test it.
39Subtyping and Assignment
subclass objects may be assigned to superclass
variables
Vehicle v1 new Vehicle() Vehicle v2 new
Car() Vehicle v3 new Bicycle()
40Casting
- Why cant Elmer breathe?
- Elmer instantiated as type LandMonster
- Elmer declared to be of type Monster
- Monsters cant breathe
- Can cast elmer as a LandMonster
- (LiveMonster) elmer
- produces an anonymous reference to a LiveMonster
object - can use it to call breathe method
- ((LiveMonster) elmer).breathe()
- Try it in project
- Why did we do this?
41Array of Monsters
- Suppose we want to use an array to hold the
collection of monsters for the mixer - All elements of the array must be of the same
type - Can all be of type Monster
- Instantiate them as objects of their specialized
subclasses - See Monsters Inc Array
- Do the monsters report on their state correctly?
- Which toString method is used?
- Why?
42instanceof
- Suppose we want to have the specialized monsters
perform their specialized tasks - e.g. have the LiveMonsters breathe
- Can we call the breathe method for all monsters?
- To detect the data type of an object, use the
instanceof operator - object instanceof Classname
- result is either true or false
- See mixer in "Monsters Inc - Array"
43Polymorphic 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. - Recall that Vectors hold Objects, and subtypes of
objects
44Polymorphism
- As in C, we can overload a method by defining
each version with a different signature. - Signature Combination of method name and type
and number of parameters - True polymorphism The same method name with the
same types and same number of parameters but with
different results depending on which subclass the
object belongs to.
45Design Hints for Inheritance
- Place common operations and fields in superclass
- Put sender field in Message class, not
TextMessage and VoiceMessage subclasses - Use inheritance to model the "is-a" relationship
- Consultant gets paid, just like employees. But
consultant is NOT an employee, shouldn't be
subclass - Don't use inheritance unless all inherited
methods make sense - If class Holiday extends Day, day.advance()
wouldn't make sense with Holiday
laborDay.advance() - Use polymorphism, not type information
- If (x is type1) action1() else if (x is type2)
action2() etc.should use polymorphic x.action()
if action1 and action2 represent a common concept.
46HW Assignment 6
- "Wheel of Fortune"
- Create 5 or more puzzles
- Help getting started (see handout)
47Test 2 in One Week
- Sample Test on Course Web Site
- Go To Course Schedule
- Answers on my Bulletin Board
- Please leave there for other students
48Java BREAK