Week 06 b - PowerPoint PPT Presentation

1 / 48
About This Presentation
Title:

Week 06 b

Description:

All monsters can move, but do they move in the same way? ... hold the collection of monsters for the mixer ... Can we call the breathe method for all monsters? ... – PowerPoint PPT presentation

Number of Views:33
Avg rating:3.0/5.0
Slides: 49
Provided by: davidh67
Category:
Tags: monsters | week

less

Transcript and Presenter's Notes

Title: Week 06 b


1
Week 06 - b
  • Vector Example
  • Class Hierarchies, Inheritance
  • Polymorphism
  • Review for Test 2

2
Sample Programs Referenced(code located in
course folder)
  • VectorRace
  • java inherit.InheritLab
  • Monsters Inc.
  • Monsters Inc. - Array

3
Example 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

4
Example 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

5
Inheritance
6
Inheritance
  • 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

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

8
Inheritance(Animated Illustrations)
  • java inherit.InheritLab

9
Hierarchies
Things
Living Things
Non-living Things
Animals
Plants
?
?
?
?
Invertebrates
Vertebrates
10
Why 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
11
Relationships
  • "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

12
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 their own attributes

13
Inheritance in Java
no change here
public class Item ...
change here
public class Video extends Item ...
public class CD extends Item ...
14
Adding more item types
15
Superclass
public class Item private String title
private int playingTime private boolean
gotIt private String comment //
constructors and methods omitted.
16
Subclasses
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.
17
Superclass 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
18
Superclass 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.

19
Subclass 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
20
Deeper hierarchies
21
Refinement 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"

22
Subclasses 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

23
Hiding Member Variables
  • class Suppper
  • double aNumber
  • . . .
  • class Subbie extends Suppper
  • int aNumber
  • . . .
  • aNumber (int)super.aNumber
  • Recall issues of Scope

24
Super-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

25
The 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.

27
Overriding 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
...
28
Overriding 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

29
Overriding 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

30
Inheritance Summary
  • Inheritance helps with
  • Avoiding code duplication
  • Code reuse
  • Easier maintenance
  • Extendibility

31
to the Computers
  • Demo (or get help with) HW

32
Java BREAK
33
Monsters, 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 ?

34
Monster 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)

35
Implementing 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?

36
Inheritance 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()

37
Overriding
  • 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

38
Overloadingreview
  • 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.

39
Subtyping and Assignment
subclass objects may be assigned to superclass
variables
Vehicle v1 new Vehicle() Vehicle v2 new
Car() Vehicle v3 new Bicycle()
40
Casting
  • 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?

41
Array 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?

42
instanceof
  • 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"

43
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.
  • Recall that Vectors hold Objects, and subtypes of
    objects

44
Polymorphism
  • 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.

45
Design 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.

46
HW Assignment 6
  • "Wheel of Fortune"
  • Create 5 or more puzzles
  • Help getting started (see handout)

47
Test 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

48
Java BREAK
Write a Comment
User Comments (0)
About PowerShow.com