Abstract Classes
An abstract class is an unfinished blueprint you cannot build directly. It sets rules and leaves some parts for the classes that inherit from it to fill in.
In this page:
Syntax
abstract class ClassName
{
public abstract ReturnType MethodName(); // no body
}
class DerivedClass : ClassName
{
public override ReturnType MethodName() { }
}
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Trying to create an object of an abstract class with
new, which is a compile error. - Not implementing every abstract member in the derived class, which is a compile error unless the class is also abstract.
- Giving an abstract method a body, which is not allowed.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: