C#
abstract methods
Learn abstract methods and overriding in derived classes.
Abstract methods
An abstract method is a method signature with no body that must be overridden in a subclass. Declaration: public abstract int Area();.
Abstract methods can only live inside an abstract class. If the subclass does not write a body as public override int Area() { ... }, you get a compile error. This guarantees that subclasses implement a specific behavior. Abstract methods cannot be private because the subclass must see them.
Override requirement
Every concrete class that inherits an abstract class must override all its abstract methods. Otherwise the compiler errors out.
Example: if you declare abstract class Shape { public abstract int Area(); }, then inside class Square : Shape you must write public override int Area() { return Side * Side; }. If you don't, you must mark Square itself as abstract. This rule guarantees the contract is fully implemented.
Exercise Square area
Add a public abstract int Area(); method to Shape. In Square write the public override int Area() body: return Side * Side;. In Main, create Shape s = new Square { Side = 4 }; and print s.Area().
Show example solution
Add `public abstract int Area();` to Shape. Add `public override int Area() { return Side * Side; }` to Square. In Main write `Shape s = new Square { Side = 4 }; Console.WriteLine(s.Area());`.
Example solution:
using System;
abstract class Shape
{
public abstract int Area();
}
class Square : Shape
{
public int Side { get; set; }
public override int Area()
{
return Side * Side;
}
}
class Program
{
static void Main()
{
Shape s = new Square { Side = 4 };
Console.WriteLine(s.Area());
}
}
Test yourself
-
Match: abstract method parts
- abstract void MakeSound
- bodyless signature
- override
- body in subclass
- missing override
- compile error
- public
- default access
-
Fill in the blank: abstract method
abstract class Shape
{
public ____ int Area();
}
Show answer
abstract class Shape
{
public abstract int Area();
}
-
Which statement about abstract methods is correct?
- An abstract method can have a body.
- An abstract method can be private.
- An abstract method is not redeclared in the implementing class.
- An abstract method is bodyless and is overridden in the implementing class.
Show answer
An abstract method is bodyless and is overridden in the implementing class. — Correct. An abstract method is bodyless and override is required.
Next lesson: virtual vs abstract