Segment firstCode:
<! --- Animal class --->
<Cfcomponent displayname = "Animal class">
<Cffunction name = "Iscarnivorous" Access = "public" returntype = "Boolean">
<Cfreturn true/>
</Cffunction>
<Cffunction name = "ispolyphagia" Access = "public" returntype = "Boolean">
<Cfreturn true/>
</Cffunction>
<Cffunction name = "says" Access = "public" returntype = "string"> </cffunction>
</Cfcomponent>
<! --- Dog class --->
<Cfcomponent displayname = "Dog class" extends = "animal">
<Cffunction name = "says" Access = "public" returntype = "string">
<Cfreturn "Wang"/>
</Cffunction>
<Cffunction name = "ispolyphagia" Access = "public" returntype = "Boolean">
<Cfreturn false/>
</Cffunction>
</Cfcomponent>
<! --- Chicken class --->
<Cfcomponent displayname = "Chicken class" extends = "animal">
<Cffunction name = "says" Access = "public" returntype = "string">
<Cfreturn "Ji"/>
</Cffunction>
<Cffunction name = "Iscarnivorous" Access = "public" returntype = "Boolean">
<Cfreturn false/>
</Cffunction>
</Cfcomponent>
<! --- Test. cfm --->
<Cfscript>
Dogobj = Createobject ("component", "dog ");
Chickenobj = Createobject ("component", "chicken ");
Writeoutput ("A dog says:" & dogobj. says () & ", is carnivorous:" & dogobj. iscarnivorous () & ", is a polyphagia:" & dogobj. ispolyphagia () & "<br/> ");
Writeoutput ("a chicken says:" & chickenobj. says () & ", is carnivorous:" & chickenobj. iscarnivorous () & ", is a polyphagia:" & chickenobj. ispolyphagia ());
</Cfscript>
The code above defines a parent class animal, which has three methods: Iscarnivorous (), ispolyphagia (), and says (). Both the Dog class and the chicken class are subclasses of the animal class. Because Iscarnivorous () and ispolyphagia () both return true, while dog is a meat-eating animal. To overload ispolyphagia (), return false. On the contrary, chicken is a miscellaneous animal and Iscarnivorous () needs to be overloaded () returns false.
Each animal has its own unique voice mode. Therefore, both the dog and chicken subclasses must overload the says () method, which is the says () defined in the parent animal class () the method does not have a function body because it is abstract.
After test. cfm is run, the following result is displayed:
A dog says: Wang, is carnivorous: True, is polyphagia: false
A chicken says: Ji, is carnivorous: false, is polyphagia: True
Summary: The ability of child classes to overload their parent classes is polymorphism. polymorphism allows subclass to use the parent class methods or overload them when these methods are insufficient. this achieves code reuse, accelerates code implementation, and isolates code.ProgramTo make program maintenance easier.
Another article about coldfusionmx PolymorphismArticle:
The benefits of polymorphism with ColdFusion Components