Interfaces and Abstractions
Abstract Classes
An abstract class can share code while requiring derived classes to fill in a method.
Abstract Classes
AbstractClasses.cs
using System;
abstract class Report
{
public string Title { get; }
protected Report(string title)
{
Title = title;
}
public abstract string Body();
public string Summary()
{
return Title + ":" + Body();
}
}
class CountReport : Report
{
private readonly int count;
public CountReport(string title, int count) : base(title)
{
this.count = count;
}
public override string Body()
{
return count + " items";
}
}
class Program
{
static void Main()
{
int count = ;
Report report = new CountReport("daily", count);
string summary = report.Summary();
Console.WriteLine($"count={count}");
Console.WriteLine($"summary={summary}");
}
}
using System;
abstract class Report
{
public string Title { get; }
protected Report(string title)
{
Title = title;
}
public abstract string Body();
public string Summary()
{
return Title + ":" + Body();
}
}
class CountReport : Report
{
private readonly int count;
public CountReport(string title, int count) : base(title)
{
this.count = count;
}
public override string Body()
{
return count + " items";
}
}
class Program
{
static void Main()
{
int count = ;
Report report = new CountReport("daily", count);
string summary = report.Summary();
Console.WriteLine($"count={count}");
Console.WriteLine($"summary={summary}");
}
}
using System;
abstract class Report
{
public string Title { get; }
protected Report(string title)
{
Title = title;
}
public abstract string Body();
public string Summary()
{
return Title + ":" + Body();
}
}
class CountReport : Report
{
private readonly int count;
public CountReport(string title, int count) : base(title)
{
this.count = count;
}
public override string Body()
{
return count + " items";
}
}
class Program
{
static void Main()
{
int count = ;
Report report = new CountReport("daily", count);
string summary = report.Summary();
Console.WriteLine($"count={count}");
Console.WriteLine($"summary={summary}");
}
}
abstract class
An abstract class can define shared behavior and abstract members.