Không giống như thừa kế, mà là một cơ chế thời gian biên dịch, đa hình là thời gian chạy khả năng của một tham chiếu đến thay đổi hành vi của nó tùy thuộc vào loại đối tượng mà hiện tại đang được giao. Định tuyến động này (hoặc ràng buộc) của tin nhắn với các phương pháp là một trong ba đặc điểm của lập trình hướng đối tượng ngoài các lớp học, thừa kế. Mặc dù đưa ra các quyết định (xét nghiệm, phân nhánh, và như vậy) tại thời gian biên dịch là rất hiệu quả, bất kỳ thay đổi có. | Polymorphism and Virtual Methods 143 hand offers only a few public services typically one that must be implemented as a contract by the subclass that derives from it. A delegate however offers a single public service1 that is not necessarily related to a particular object or interface. From a caller s point of view it is only necessary to match the signature of a method with that of the delegate. Polymorphism and Virtual Methods Unlike inheritance which is a compile-time mechanism polymorphism is the runtime ability of a reference to vary its behavior depending on the type of object that is currently assigned to it. This dynamic routing or binding of messages to methods is one of the three hallmarks of object-oriented programming in addition to classes and inheritance. Although making decisions tests branching and so on at compile-time is very efficient any change may require considerable recompilation. On the other hand with polymorphism decisions can be changed at runtime and routed to the correct behavior. Dynamic binding does come with some computational overhead. However faster processors larger memories and better compilers have reduced this cost considerably. Nonetheless tools such as profilers are very helpful in pinpointing those sections of code that can afford the luxury of polymorphism. In any case it is always worthwhile to investigate the possibility since polymorphism leads to software that is more flexible extendable and easier to maintain in the long run. When a class is designed it is advantageous to make methods polymorphic or Tip virtual. Therefore if a method is inherited and does not satisfy the specific requirements of the derived class it can be redefined and reimplemented. Such a method is said to be overridden. In Chapter 4 methods for the BoundedCounter class were inherited as is from their base class Counter. In this section we examine how methods are overridden using the modifier override to redefine the behavior of virtual .