Polymorphism (computer science): Difference between revisions

Content deleted Content added
m Section heading change: Rank Polymorphism → Rank polymorphism using a script
Subtyping: add UML image
Line 89:
In the following Java example we make cats and dogs subtypes of animals. The procedure <code>letsHear()</code> accepts an animal, but will also work correctly if a subtype is passed to it:
 
<syntaxhighlight lang="Javajava">
abstract class AnimalPet {
abstract String talkspeak();
}
 
class Cat extends AnimalPet {
String talkspeak() {
return "Meow!";
}
}
 
class Dog extends AnimalPet {
String talkspeak() {
return "Woof!";
}
}
 
static void letsHear(final AnimalPet apet) {
println(apet.talkspeak());
}
 
Line 115:
}
</syntaxhighlight>
 
[[File:UML class pet.svg]]
 
In another example, if ''Number'', ''Rational'', and ''Integer'' are types such that ''Number''&nbsp;:&gt;&nbsp;''Rational'' and ''Number''&nbsp;:&gt;&nbsp;''Integer'', a function written to take a ''Number'' will work equally well when passed an ''Integer'' or ''Rational'' as when passed a ''Number''. The actual type of the object can be hidden from clients into a [[Black box (systems)|black box]], and accessed via object [[identity (object-oriented programming)|identity]].