C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: In the example, the class A is the base class. It has the virtual method Y.
VirtualAnd: In class B, we override Y. In class C, we implement Y but do not specify that it overrides the base method.
ClassC# program that uses override modifier
using System;
class A
{
public virtual void Y()
{
// Used when C is referenced through A.
Console.WriteLine("A.Y");
}
}
class B : A
{
public override void Y()
{
// Used when B is referenced through A.
Console.WriteLine("B.Y");
}
}
class C : A
{
public void Y() // Can be "new public void Y()"
{
// Not used when C is referenced through A.
Console.WriteLine("C.Y");
}
}
class Program
{
static void Main()
{
// Reference B through A.
A ab = new B();
ab.Y();
// Reference C through A.
A ac = new C();
ac.Y();
}
}
Output
B.Y
A.Y
Note: The override modifier was not used. The C.Y method is local to the C type.
Warning: The C type generates a warning because C.Y hides A.Y. Your program is confusing and could be fixed.
Tip: If you want C.Y to really "hide" A.Y, you can use the new modifier, as in "new public void Y()" in the declaration.
NewTip: I recommend writing a test program to see how this works. This may help you understand.
Quote: Whereas a virtual method introduces a new method, an override method specializes an existing inherited virtual method by providing a new implementation of that method (The C# Programming Language).