Jump to content

Polymorphism in object-oriented programming

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Lee Daniel Crocker (talk | contribs) at 23:34, 20 December 2001. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

In object-oriented programming theory, polymorphism refers to the ability

for references and collections to hold objects of different types, and for the

methods invoked on those references to find the right type-specific behavior at

run time (this latter feature is called late binding or dynamic binding).


For example, in Java, if you define

Cow and Pig types as subclasses of Animal

(see inheritance) like this:


 class Cow extends Mammal {
   public Tail m_tail;
   private Horns m_horns;


   public void eat(Food f) {
     if (f.is_meat()) {
       return; // Cow won't eat
     }
     super.eat(f);
     chewcud();
   }
   private void chewcud() {
     . . .
   }
 }
 class Pig extends Mammal {
   // No need to override Animal's eat()
   // function here; pigs will eat anything.
 }



Then you can declare a single variable that takes objects of either type,

and call methods on that variable, like this:


 Animal theAnimal = new Pig();
 theAnimal.eat(table_scraps);
 theAnimal = new Cow();
 theAnimal.eat(table_scraps);


In the above code, when the eat()method is called on theAnimal

the first time (when it references the pig), the Pig class's eat(),

method will be called, which will accept the table scraps.

When theAnimal is reset to point to the cow, Cow's eat()

method is called instead, and it will reject the table scraps.


Lots more to be said here, including generics...