C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Methods: Abstract methods cannot have bodies. This makes sense: these bodies would never be used.
Classes: Abstract classes have certain restrictions. They cannot be constructed directly.
Note: When we derive a class like Example1 or Example2, we must provide override methods for all abstract methods in the abstract class.
Tip: In this program, the A() method in both derived classes satisfies this requirement.
C# program that uses abstract class
using System;
abstract class Test
{
public int _a;
public abstract void A();
}
class Example1 : Test
{
public override void A()
{
Console.WriteLine("Example1.A");
base._a++;
}
}
class Example2 : Test
{
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();
// Reference Example2 through Test type.
Test test2 = new Example2();
test2.A();
}
}
Output
Example1.A
Example2.A
C# program that causes compilation error
abstract class Test
{
public abstract void A();
}
class Example1 : Test
{
}
class Program
{
static void Main()
{
}
}
Output
error CS0534:
'Example1' does not implement inherited abstract member 'Test.A()'
And: An interface cannot have fields. An abstract class is the same thing as an interface except it is a class, not just a contract.
Tip: We show that performance remains the same with an abstract class instead of a regular class.
InterfaceSo: In solving the problem of code duplication among many object types, abstract classes help improve code quality and performance.