Object-Oriented Programming (OOP) Part 2: Advanced
7 min read
Welcome back, coder! ☕️
In Part 1, we learned how to build a class—a blueprint for an object. But real software isn't just one lonely object floating in the void. It's a complex ecosystem of objects interacting, sharing logic, and transforming.
Imagine building a Role-Playing Game (RPG). You have Warriors, Mages, and Archers. If you write separate code for every single movement and health check for each of them, you will develop Carpal Tunnel Syndrome before you finish the tutorial level.
Today, we are moving from writing words to writing sentences. We are going to organize our code to be reusable, flexible, and scalable.
1. Inheritance: Reusing and Extending Classes
The Problem: The Copy-Paste Nightmare
Imagine you are coding your RPG.
You create a Warrior class with Health, Name, and a method Move().
Then you create a Mage class. It also needs Health, Name, and Move().
Then an Archer...
You are violating the DRY Principle (Don't Repeat Yourself). If you find a bug in the Move() logic, you have to fix it in three different files. 😫
The Solution: Inheritance
Definition: Inheritance is a mechanism where a new class (derived/child) acquires the properties and methods of an existing class (base/parent).
It establishes an "Is-A" relationship. A Warrior is a Character.
💻 The Concept in Action
Let's create a generic Character (Base Class) and let specific classes inherit from it.
// Base Class (Parent)
public class Character
{
public string Name { get; set; }
public int Health { get; set; }
public void Move()
{
Console.WriteLine($"{Name} is moving forward.");
}
}
// Derived Class (Child)
// The syntax ": Character" means Warrior inherits from Character
public class Warrior : Character
{
public int Armor { get; set; } // Specific to Warrior
public void Bash()
{
Console.WriteLine($"{Name} bashes with a shield!");
}
}
// Derived Class (Child)
public class Mage : Character
{
public int Mana { get; set; } // Specific to Mage
public void CastSpell()
{
Console.WriteLine($"{Name} casts a fireball!");
}
}🛠️ Industry Practice: How to use it
// Usage
var conan = new Warrior();
conan.Name = "Conan";
conan.Health = 100;
// Conan has the Move() method even though we didn't write it inside Warrior!
conan.Move(); // Output: Conan is moving forward.
conan.Bash(); // Output: Conan bashes with a shield!🧠 Under the Hood: When you create an instance of
Warrior, C# actually allocates memory for the base class (Character) fields first, and then appends the derived class (Warrior) fields. It's like adding an extension to an existing house.
2. Polymorphism: Method Overriding and Virtual Methods
The Problem: The Boring Robot
Currently, Warrior and Mage both inherit Move(). But what if the Mage shouldn't just "move"? What if the Mage "floats"?
If you treat a List<Character>, you want to call Move() on everyone, but you want them to behave according to their specific type.
The Solution: Polymorphism
Definition: Polymorphism (Greek for "many forms") allows objects to be treated as instances of their parent class while executing their specific child-class behavior at runtime.
The Concept: virtual and override
To allow a child to change a parent's behavior, we need a permission slip and a declaration.
virtual: Added to the Parent method. Means "I allow my children to change this."override: Added to the Child method. Means "I am changing the behavior defined in my parent."
💻 The Concept in Action
public class Character
{
public string Name { get; set; }
// Permission granted to override
public virtual void Attack()
{
Console.WriteLine($"{Name} punches generically.");
}
}
public class Warrior : Character
{
// Changing the behavior
public override void Attack()
{
Console.WriteLine($"{Name} swings a giant sword!");
}
}
public class Mage : Character
{
public override void Attack()
{
Console.WriteLine($"{Name} throws a fireball!");
}
}🛠️ Industry Practice: The "Poly" Magic
This is where the magic happens. We can create a list of the generic type Character, but the specific override methods will run.
List<Character> party = new List<Character>
{
new Warrior { Name = "Aragorn" },
new Mage { Name = "Gandalf" },
new Character { Name = "Villager" } // The base class
};
foreach (var hero in party)
{
// MAGIC: The compiler doesn't know which Attack() to call until the app runs.
hero.Attack();
}
/* OUTPUT:
Aragorn swings a giant sword!
Gandalf throws a fireball!
Villager punches generically.
*/💡 Fun Fact: This is called Dynamic Dispatch. C# maintains a "V-Table" (Virtual Method Table) in memory. When
Attack()is called, it looks up this table to find the correct version of the function for that specific object type.
3. Abstract Classes: Partial Blueprints
The Problem: The Phantom Object
Look at the list above. We created new Character { Name = "Villager" }.
In a real RPG, you should never have just a "Character." Is it a monster? A hero? An NPC?
It’s too vague. We want to share the code for Name and Health, but we want to forbid anyone from creating just a plain Character.
The Solution: Abstract Classes
Definition: An abstract class is a class that cannot be instantiated (you can't say new MyClass()). It is designed strictly to be inherited from.
💻 The Concept in Action
// You cannot do: var c = new Character(); -> Compiler Error 🛑
public abstract class Character
{
public string Name { get; set; }
public void Sleep()
{
Console.WriteLine("Zzzzz..."); // Shared logic is fine!
}
// Abstract Method: No code body allowed!
// It forces the child to implement it.
public abstract void Attack();
}
public class Warrior : Character
{
// We MUST override Attack, or the compiler will yell at us.
public override void Attack()
{
Console.WriteLine("Sword Slash!");
}
}🛠️ Industry Practice
Use Abstract classes when you have a strong "Is-A" relationship and you want to provide some default logic (like Sleep) but enforce specific logic for other things (like Attack).
4. Interfaces: Defining Contracts
The Problem: The "Multiple Inheritance" Trap
In C#, a class can only inherit from one parent (e.g., Warrior can't be both Character and DestructibleObject). This avoids the messy "Diamond Problem" found in C++.
But what if a Chest can be "Opened" and a Door can be "Opened"? They aren't related classes, but they share a capability.
The Solution: Interfaces
Definition: An Interface is a contract. It defines a set of signatures (methods/properties) that a class must implement. It does not (usually) contain implementation logic.
It defines "Can-Do" behavior, not "Is-A" identity.
💻 The Concept in Action
Naming convention: Always start with an I.
// The Contract
public interface IOpenable
{
void Open(); // Just the signature. No body.
}
// The Chest respects the contract
public class Chest : IOpenable
{
public void Open()
{
Console.WriteLine("Creak... You found gold!");
}
}
// The Door respects the contract
public class Door : IOpenable
{
public void Open()
{
Console.WriteLine("The door unlocks.");
}
}🛠️ Industry Practice: Dependency Injection
Interfaces are massive in professional C#. They allow us to decouple code.
Imagine you are saving game data.
public interface IDataSaver
{
void Save(string data);
}
public class CloudSaver : IDataSaver
{
public void Save(string data) { /* Send to AWS */ }
}
public class DiskSaver : IDataSaver
{
public void Save(string data) { /* Write to HDD */ }
}
public class GameManager
{
private readonly IDataSaver _saver;
// We don't care IF it's cloud or disk. We just want something that saves.
public GameManager(IDataSaver saver)
{
_saver = saver;
}
public void SaveGame()
{
_saver.Save("Player Level: 99");
}
}🔥 Hot Tip: Always prefer Composition over Inheritance where possible. Interfaces make your code flexible. If you inherit, you are stuck with that parent forever. If you use interfaces, you can plug and play different behaviors.
Summary: Which one do I use?
| Concept | Keyword | Metaphor (Rules permitting) | Use Case |
|---|---|---|---|
| Inheritance | class B : A |
The DNA | When B is an A and shares most logic. |
| Polymorphism | virtual / override |
The Shape-shifter | When children need to do the same thing differently. |
| Abstract Class | abstract |
The Blueprint | When the base concept is too vague to exist alone. |
| Interface | interface |
The Contract | When unrelated things share a capability (Can-Do). |
📚 References & Further Reading
- Inheritance (Microsoft Docs): learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/inheritance
- Polymorphism (Microsoft Docs): learn.microsoft.com/en-us/dotnet/csharp/fundamentals/object-oriented/polymorphism
- Interfaces: learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/interfaces
- Abstract Classes: learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/abstract
Now, go forth and refactor that spaghetti code! 🍝 -> 🏛️
Challenge
You are tasked with designing a flexible document management system. Your goal is to model different types of documents using advanced Object-Oriented Programming principles.
Requirements:
Create an Abstract Base Class:
- Define an
abstractclass namedDocument. - It must contain two public
stringproperties:TitleandAuthor. - It must have a concrete public method
GetSummary()that returns a string in the format:"[Title] by [Author]". - It must declare a public
abstractmethodPrint()that returnsvoid.
- Define an
Define a Contract for Encryption:
- Create a public
interfacenamedIEncryptable. - This interface must define two
voidmethod signatures:Encrypt()andDecrypt().
- Create a public
Implement Concrete Document Classes:
PDFDocument: This class must inherit fromDocumentand implement theIEncryptableinterface.WordDocument: This class must inherit fromDocumentand implement theIEncryptableinterface.ImageDocument: This class must inherit fromDocumentbut should not implementIEncryptable.
Provide Method Implementations:
- For each of the three concrete classes, you must provide a specific implementation for the
Print()method. - For
PDFDocumentandWordDocument, you must also provide implementations for theEncrypt()andDecrypt()methods.
- For each of the three concrete classes, you must provide a specific implementation for the
Expected result
Your final code should consist of one abstract class, one interface, and three concrete classes that meet all the specified requirements.
An
abstract classnamedDocumentwith:- Public string properties
TitleandAuthor. - A public method
GetSummary()returning a formatted string. - An
abstractpublic methodPrint().
- Public string properties
A public
interfacenamedIEncryptablewith:- Method signatures for
Encrypt()andDecrypt().
- Method signatures for
A
public class PDFDocumentthat:- Inherits from
Document. - Implements
IEncryptable. - Provides a concrete implementation for
Print(),Encrypt(), andDecrypt().
- Inherits from
A
public class WordDocumentthat:- Inherits from
Document. - Implements
IEncryptable. - Provides a concrete implementation for
Print(),Encrypt(), andDecrypt().
- Inherits from
A
public class ImageDocumentthat:- Inherits from
Document. - Provides a concrete implementation for
Print().
- Inherits from