Java Reference
In-Depth Information
After sorting on first, then last name using null first...
null
null
Jacobs, Jeff
Jacobs, John
Inman, Wally
Polymorphism—One Object, Many Views
Polymorphism refers to the ability of an object to take on many forms. I will use the term “view” instead of the term
“form.” The term “view” gives better understanding of polymorphism in the context of interfaces. Let's rephrase
the definition of polymorphism: It is an ability of an object to provide its different views. Interfaces let you create a
polymorphic object. Consider the Turtle class declaration shown in Listing 17-21. It implements Swimmable and
Walkable interfaces. You create a Turtle object as shown:
Turtle turti = new Turtle("Turti");
Because the Turtle class implements the Walkable and Swimmable interfaces, you can treat the turti object as a
Walkable or a Swimmable .
Walkable turtiWalkable = turti;
Swimmable turtiSwimmable = turti;
Since every class in Java is inherited from the Object class, you can also treat the turti object as an Object .
Object turiObject = turti;
Figure 17-3 shows four different views of the same Turtle object. Note that there is only one object, which is of
the Turtle class. When you look at a house from different directions (top, front, back, left, right, etc.), you get different
views of the same house. Nevertheless, there is only one house. Note that when you are looking at a house from its
front, you do not get to see its other views, from example, the back view or the left view. Like a house, a Java object can
exhibit different views of itself, which is called polymorphism.
A Turtle view - All methods in the Turtle class
bite( )
Walkable
view
Swimmable
view
A Turtle
object
swim( )
walk( )
Inherited methods from the Object
class: hashCode( ) , toString( ) ,
equals( ) , etc.
Object view
Figure 17-3. Polymorphism— one object, many views. Four different views of a Turtle object
 
Search WWH ::




Custom Search