Revised: Thu Mar 31 11:49:25 CDT 2016
This page is included in the following Books:
Table of contents
- Preface
- Preview
- Discussion and sample code
- Summary
- What's next?
- Miscellaneous
- Complete program listings
Preface
This module is one of a series of modules designed to teach you about the essence of Object-Oriented Programming (OOP) using Java.
Viewing tip
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the listings while you are reading about them.
Listings
- Listing 1 . Definition of the class named A.
- Listing 2 . Definition of the class named B.
- Listing 3 . Definition of the class named C.
- Listing 4 . Beginning of the class named Poly02.
- Listing 5 . An illegal operation.
- Listing 6 . An ineffective downcast.
- Listing 7 . A downcast to type B.
- Listing 8 . Declare a variable of type B.
- Listing 9 . Cannot be assigned to type C.
- Listing 10 . Another failed attempt.
- Listing 11 . Complete program listing.
Preview
This module discusses type conversion for both primitive and reference types.
A value of a particular type may be assignment compatible with variables of other types, in which case the value can be assigned directly to the variable. Otherwise, it may be possible to perform a cast on the value to change its type and assign it to the variable as the new type.
With regard to reference types, whether or not a cast can be successfully performed
- depends on the relationships of the classes involved in the class hierarchy.
A reference to any object can be assigned to a reference variable of the type Object , because the Object class is a superclass of every other class.
When we cast a reference along the class hierarchy in a direction from the root class Object toward the leaves, we often refer to it as a downcast .
Whether or not a method can be called on a reference to an object depends on
- the current type of the reference, and
- the location in the class hierarchy where the method is defined.
In order to use a reference of a class type to call a method, the method must be defined at or above that class in the class hierarchy.
A sample program is provided that illustrates much of the detail involved in type conversion, method calls, and casting with respect to reference types.
Discussion and sample code
What is polymorphism?
As a quick review, the meaning of the word polymorphism is something like one name, many forms .
How does Java implement polymorphism?
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods, which were discussed in a previous module) .