Abstract
Abstract Class
- A class declared as abstract can never be instantiated. Instead, only its concrete subclasses can be instantiated.
- Specifies method signatures but lacks implementation.
- It is used as a template for derived classes(base class).
- Abstract class can have abstract and virtual members.
- The subclass must provide implementation unless declared abstract
Abstract Methods
- Abstract members cannot be private.
- Abstract methods are implicitly virtual.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
new Stock { SharesOwned = 200, CurrentPrice = 123.45M }.NetValue.Dump();
}
}
public abstract class Asset
{
public abstract decimal NetValue { get; }
}
public class Stock : Asset
{
public long SharesOwned;
public decimal CurrentPrice;
//override virtual method
public override decimal NetValue => CurrentPrice * SharesOwned;
}
}
Abstract Properties
//Abstract Class with abstract properties
abstract class absClass
{
protected int myNumber;
public abstract int numbers
{
get;
set;
}
}
class absDerived:absClass
{
//Implementing abstract properties
public override int numbers
{
get
{
return myNumber;
}
set
{
myNumber = value;
}
}
}
Rules:
- Abstract class cannot be sealed.
- Abstract methods are only allowed in abstract classes.
- Abstract methods cannot be private.
- Access modifier of the abstract method should be same in both abstract class and its derived class.
- Abstract member cannot be static.
- Abstract method cannot have virtual modifier.
Read more about Interface vs Abstract in Interface article.