Polymorphism
One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.
C# Example
Let's assume the following simple classes A and B for the discussions in this text. A is the base class, B is derived from A.
Inherited Methods
A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } }
class B : A {}
class Test { static void Main(string[] args) { A a = new A(); a.Foo(); // output --> "A::Foo()"
B b = new B(); b.Foo(); // output --> "A::Foo()" } } }
The method Foo() can be overridden in classes B and C:
using System; namespace Polymorphism { class A { public void Foo() { Console.WriteLine("A::Foo()"); } }
class B : A { public void Foo() { Console.WriteLine("B::Foo()"); } }
class Test { static void Main(string[] args) { A a; B b;
a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()"
a = new B(); a.Foo(); // output --> "A::Foo()" } } }
There are two problems with this code.
The output is not really what we, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual.
Although the code compiles and runs, the compiler produces a warning: ...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
using System; namespace Polymorphism { class A { public virtual void Foo() { Console.WriteLine("A::Foo()"); } }
class B : A { public override void Foo() { Console.WriteLine("B::Foo()"); } }
class Test { static void Main(string[] args) { A a; B b;
a = new A(); b = new B(); a.Foo(); // output --> "A::Foo()" b.Foo(); // output --> "B::Foo()"
a = new B(); a.Foo(); // output --> "B::Foo()" } } }
For more details, visit http://matespoint.blogspot.com/2008/06/polymorphism-method-hiding-and.html
|
No responses found. Be the first to respond and make money from revenue sharing program.
|