OOP: Polymorphism & Interfaces
Polymorphism allows objects to take on many forms. C# supports abstract classes and interfaces to implement polymorphism and establish clean contracts.
1 Abstract Classes vs. Interfaces
C# provides two abstraction frameworks:
- Abstract Class: A class declared `abstract` that cannot be instantiated. Can contain constructor fields, instance states, and fully defined methods.
- Interface: A contract definition. Interfaces contain no instance fields (only static final constants) and by default specify abstract signatures. Classes implement interfaces using the `implements` keyword. A class can implement multiple interfaces.
2 Polymorphism Code
Let's run a program illustrating interfaces and dynamic runtime dispatch polymorphism:
C# — Interfaces & Abstractions
▶ Run Code
using System;
interface IDrivable {
void Drive(); // Interface abstract method
}
class Car : IDrivable {
public void Drive() {
Console.WriteLine("Car is driving on roads.");
}
}
class Boat : IDrivable {
public void Drive() {
Console.WriteLine("Boat is cruising on water.");
}
}
class Program {
static void Main() {
IDrivable v1 = new Car();
IDrivable v2 = new Boat();
v1.Drive();
v2.Drive();
}
}
3 Code Challenge
Challenge: Write an interface called `IPaymentMethod` with a method `Pay(double amount)`. Create classes `CreditCard` and `PayPal` implementing the interface, and write a dynamic payment simulation.