The same message (in this case, move) sent to a variety of objects has "many forms" of results-hence the term polymorphism. Relying on each object to know how to "do the right thing" (i.e., do what is appropriate for that type of object) in response to the same method call is the key concept of polymorphism. The program issues the same message (i.e., move) to each animal object generically, but each object knows how to modify its x-y coordinates appropriately for its specific type of movement. However, each specific type of Animal responds to a move message in a unique way-a Fish might swim three feet, a Frog might jump five feet and a Bird might fly ten feet. To simulate the animals' movements, the program sends each object the same message once per second-namely, move. Our program maintains an array of references to objects of the various Animal subclasses. Imagine that each of these classes extends superclass Animal, which contains a method move and maintains an animal's current location as x-y coordinates. Classes Fish, Frog and Bird represent the three types of animals under investigation. Suppose we create a program that simulates the movement of several types of animals for a biological study. Polymorphism enables us to "program in the general" rather than "program in the specific." In particular, polymorphism enables us to write programs that process objects that share the same superclass in a class hierarchy as if they are all objects of the superclass this can simplify programming.Ĭonsider the following example of polymorphism. We now continue our study of object-oriented programming by explaining and demonstrating polymorphism with inheritance hierarchies. 10.8 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System.10.7.8 Common Interfaces of the Java API.10.7.7 Declaring Constants with Interfaces.10.7.6 Using Interface Payable to Process Invoices and Employees Polymorphically.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |