Polymorphism - What is polymorphism? - Examples - public, private, and protected - PowerPoint PPT Presentation

1 / 10
About This Presentation
Title:

Polymorphism - What is polymorphism? - Examples - public, private, and protected

Description:

Polymorphism - What is polymorphism? - Examples - public, private, and protected How is it done in Java? Done automatically!!! COOL STUFF!!! Example - BankAccount ... – PowerPoint PPT presentation

Number of Views:188
Avg rating:3.0/5.0
Slides: 11
Provided by: RM26
Category:

less

Transcript and Presenter's Notes

Title: Polymorphism - What is polymorphism? - Examples - public, private, and protected


1
Polymorphism- What is polymorphism?- Examples
- public, private, and protected
2
Polymorphic - the quality or state of existing in
or assuming different forms.
Polymorphism - In object-oriented programming,
the term is used to describe a variable that may
refer to objects whose class is not known at
compile time and which respond at run time
according to the actual class of the object to
which they refer.
3
How is it done in Java?
  • Done automatically!!! COOL STUFF!!!
  • Early Binding the compiler knows what kind of
    object is used and calls the appropriate method.
  • Late (or Dynamic) Binding as the program is
    running, the Java Virtual Machine (JVM) selects
    the appropriate method.

4
Example - GridWorld
public void step() lt other code not shown
gt // Get all the Locations where there
are Actors in the // Grid and ask each one to
perform the actions it does // in one
timestep. ArrayList ltLocationgt
occupiedLocs theGrid.getOccupiedLo
cations() for ( Location loc
occupiedLocs ) if(
theGrid.get(loc) ! null )
theGrid.get(loc).act() // Note!! All kinds
of objects here!!
5
Example - BankAccount
CheckingAccount cAcct new CheckingAccount
() BankAccount myAcct myAcct cAcct
Is this ok???
6
Example - BankAccount
CheckingAccount cAcct cAcct new BankAccount()
How about this???
7
Exercise
  • Consider the classes below

8
Exercise
  • Given the classes on the previous slide, are
    these following statements valid?

Taxable assets new Taxable5 assets0
new Stock() assets1 new RealEstate().. for
(int i 0i lt assets.length i) double d
assetsi.computeTax()
9
Casting
  • We know the following assignment is OK.
  • Taxable oneAsset new Stock()
  • oneAsset.computeTax() // Ok
  • oneAsset.getStockPrice()// Not Ok
  • // Cast it to Stock and then call
  • // method
  • if (oneAsset instanceof Stock)
  • ((Stock)oneAsset).getStockPrice()

10
A final word
  • private members in the super class are not
    accessible in the subclass.
  • protected members in the super class
  • Are accessible in the subclass.
  • Are not accessible outside the package.
  • public members of a class are accessible from
    anywhere (that you are using an object)
Write a Comment
User Comments (0)
About PowerShow.com