The Beginning use of Polymorphism

      When the implementation for the same member signature varies between two or more classes, you have a key object-oriented principal: polymorphism. Poly" meaning many and "morph" meaning form, polymorphism refers to the fact that there are multiple implementations of the same signature. And since the same signature cannot be used multiple times within a single class, each implementation of the member signature occurs on a different class.

      The idea behind polymorphism is that the object itself knows best how to perform a particular operation. Given multiple types of documents, each document type class knows best how to perform a Print() method for its corresponding document type. Therefore, instead of defining a single print method that includes a switch statement with the special logic to print each document type, with polymorphism you call the Print() method corresponding to the specific type of document you wish to print. For example, calling Print() on a word processing document class behaves according to word processing specifics, and calling the same method on a graphics document class will result in print behavior specific to the graphic. Given the document types, however, all you have to do to print a document is to call Print(), regardless of the type.

      Moving the custom print implementation out of a switch statement offers several maintenance advantages. First, the implementation appears in the context of each document type's class rather than in a location far removed; this is in keeping with encapsulation. Second, adding a new document type doesn't require a change to the switch statement. Instead, all that is necessary is for the new document type class to implement the Print() signature.

OK.Now ,let me have some test.

Code


Result you will print:

With Polymorphism , you can call the method on the base class but the implementation is specific to the derived class.

posted on 2009-04-26 15:08  冠华仔  阅读(272)  评论(0编辑  收藏  举报

导航