Abstract and Override Methods in C#
Abstract methods have no implementations. The implementation logic is provided rather by classes that derive from them. We use an abstract class to create a base template for derived classes.
Example
We introduce first an abstract class named Test. Two other classes derive from Test: the Example1 and Example2 classes. In the Test class, we have a field and also an abstract method.
Abstract methods cannot have bodies. This makes sense because those bodies would never be used.
using System;
abstract class Test
{
public int _a;
public abstract void A();
}
{
public int _a;
public abstract void A();
}
class Example1 : Test
{
public override void A()
{
Console.WriteLine("Example1.A");
base._a++;
}
}
{
public override void A()
{
Console.WriteLine("Example1.A");
base._a++;
}
}
class Example2 : Test
{
public override void A()
{
Console.WriteLine("Example2.A");
base._a--;
}
}
{
public override void A()
{
Console.WriteLine("Example2.A");
base._a--;
}
}
class Program
{
static void Main()
{
// Reference Example1 through Test type.
Test test1 = new Example1();
test1.A();
{
static void Main()
{
// Reference Example1 through Test type.
Test test1 = new Example1();
test1.A();
// Reference Example2 through Test type.
Test test2 = new Example2();
test2.A();
}
}
Test test2 = new Example2();
test2.A();
}
}
Output
Example1.A
Example2.A
Example2.A
When you create a derived class like Example1 or Example2, you must provide an override method for all abstract methods in the abstract class. The A() method in both derived classes satisfies this requirement.
No comments:
Post a Comment