Abstract Classes
In this page:
Abstract Classes
An abstract class cannot be instantiated directly and may declare abstract methods that have no body — derived classes are *required* to implement them. Abstract classes model a shared concept that only makes sense through its concrete subtypes, like Shape without a specific area formula. They can still contain regular, fully-implemented methods alongside abstract ones.
Warning: Trying to write new Shape() on an abstract Shape class is a compile error.
Example: Abstract Classes
using System;
abstract class Shape
{
public abstract double Area();
public void Describe()
{
Console.WriteLine($"Area is {Area()}");
}
}
class Square : Shape
{
public double Side;
public Square(double side)
{
Side = side;
}
public override double Area()
{
return Side * Side;
}
}
class Program
{
static void Main(string[] args)
{
Square sq = new Square(4);
sq.Describe();
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: