6.9.08

Virtual and Overridden Methods in C#.NET

  • 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; [two function with the same name inside a class]

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= new A();

B b= new B();

a.Foo(); // output --> "A::Foo()"

b.Foo(); // output --> "B::Foo()"

a = new B();

a.Foo(); // output --> "B::Foo()"

}

}

}

No comments: