Junior — Middle
Could you demonstrate an example for each of the main paradigms of object-oriented programming?
sobes.tech AI
Answer from AI
The main paradigms of object-oriented programming (OOP) are encapsulation, inheritance, and polymorphism. Here is an example in C# for each:
Encapsulation — hiding internal implementation and providing access through methods:
class BankAccount
{
private decimal balance;
public void Deposit(decimal amount)
{
if (amount > 0)
balance += amount;
}
public decimal GetBalance()
{
return balance;
}
}
Inheritance — creating a new class based on an existing one:
class Animal
{
public virtual void Speak() => Console.WriteLine("Some sound");
}
class Dog : Animal
{
public override void Speak() => Console.WriteLine("Bark");
}
Polymorphism — the ability to use objects of different classes through a common interface:
void MakeAnimalSpeak(Animal animal)
{
animal.Speak();
}
MakeAnimalSpeak(new Dog()); // Outputs "Bark"
These examples demonstrate the key concepts of OOP in C#.