5.2. Polymorphism and Virtual Methods

As the name suggests, polymorphism is the ability to have multiple (poly) faces (morphs). In the context of OOP languages, this means that the behavior of a method of a class can be changed at runtime depending on the object on which it is called. In Chapter 4 you learned about the concept of object references and instances. A reference is a pointer to the actual instance. In OOP, you can have a reference to a superclass and assign an instance of the subclass to that reference:

Shape s = new Circle();
s.draw();

Here, Shape is a superclass having one subclass, Circle. There is a draw() method in the Shape class, and there is a draw() method in the Circle class. When you call the draw() method on the reference, ...

Get .NET for Java Developers: Migrating to C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.