Object Oriented Programming is easy as P.I.E. (Polymorphism, Inhereitence, and Encapsulation)
This small sample demonstrates three core OOP concepts using a simple Duck hierarchy:
- Polymorphism — different duck types override common behaviors.
- Inhereitence — concrete ducks inherit state/behavior from the base
Duck. - Encapsulation — fields are backed by properties with validation and controlled access.
- How a base class defines common behavior and state.
- How derived classes override behavior (polymorphism).
- How to hide internal state and expose controlled accessors (encapsulation).
- Ducks/Ducks/Duck.cs — base
Duckclass and derivedMallard,Wooden,Rubber(encapsulation, inheritance, polymorphism examples). - Ducks/Ducks/Program.cs — small runnable demo showing polymorphism and property validation.
- Ducks/Ducks/Properties/AssemblyInfo.cs — assembly metadata (author and dates).
From the repository root run:
cd Ducks
dotnet build Ducks.csproj
dotnet run --project Ducks.csprojThe program prints short messages demonstrating each concept. Look at how MakeSound() and Fly() are called on the base Duck reference but produce different results per concrete duck — that is polymorphism. The Rubber class shows encapsulation by controlling its Name property (defaulting invalid names). The Mallard and Wooden classes illustrate inheritance from the common Duck base.
- Polymorphism: search for
public virtual void MakeSound()and theoverrideimplementations in derived classes. - Inhereitence: note how
Mallard,Wooden, andRubbersimply declare: Duckand reuse base behavior. - Encapsulation: inspect private backing fields (e.g.,
_name) and the corresponding public propertyNameinRubber.
Author: Joe Valentine Original: 2017 Updated: Feb 22, 2026
If this project helped you, please consider buying me a coffee: