CIS 26
Object-Oriented Programming
Polymorphism
Consequenceas of Polymorphism
Some Preliminaries
- Subtypes
- Type T1 is a subtype of T2 if every value of T1 is also a legitimate value
of T2.
- Class extension (inheritance) reflects a subtype relationship
- The subclass is a subtype of the superclass
- Methods Overriding
- Introducing a method into the subclass with the exact same signature and return type
as a method in the superclass
toString
- Note this is NOT the same as overloading
Polymorphic assignment
- The type of the variable on the right-hand-side must be a subtype of the type of the
variable on the left-hand-side
Why upcast?
- Passing subtype to method expecting supertype
- The collections all expect
Obect
s
- Assigning to an array of the supertype
- Basically an array is a collection too\
Why downcast?
Assigning from a method that returns a supertype
Obect
s are extracted from the collections
Polymorphic method invocation
- Binding of the invocation of an overridden method to the actual method body (i.e., implementation) is done at runtime
- The method must be known to the receiver class or a compiler error will result
Putting it All into Perspective
class MyApplet extends Applet {
...
}
- Browser knows about
Applet
- Browser (actually a plug-in) is Java aware
- Not
MyApplet
- You just coded it today, browser's been around much longer
- How does the broswer work with
MyApplet
?
browser creates a MyApplet
object and assigned it
to an Applet
object
Applet app = Applet.load("MyApplet.class"); // rhs returns an object
// of type MyApplet
- upcast, perfectly legal
- The 'magic' is how the object is created from the '.class' file,
nothing else
Then the browser invokes init
app.init();
- The (static) type of
app
is ???
- The (dynamic) type of the object app references is ???
And voila, control is passed to MyApplet!!