using System;
namespace OOPExample
{
// Base class
public class Animal
{
// Encapsulation: private field
private string name;
// Encapsulation: public property
public string Name
{
get { return name; }
set { name = value; }
}
// Encapsulation: method
public virtual void Speak()
{
Console.WriteLine("The animal makes a sound.");
}
}
// Derived class inheriting from Animal
public class Dog : Animal
{
// Method overriding (Polymorphism)
public override void Speak()
{
Console.WriteLine("The dog barks.");
}
}
// Derived class inheriting from Animal
public class Cat : Animal
{
// Method overriding (Polymorphism)
public override void Speak()
{
Console.WriteLine("The cat meows.");
}
}
class Program
{
static void Main(string[] args)
{
// Creating objects of derived classes
Dog myDog = new Dog();
myDog.Name = "Buddy";
Console.WriteLine(myDog.Name);
myDog.Speak(); // Outputs: The dog barks.
Cat myCat = new Cat();
myCat.Name = "Whiskers";
Console.WriteLine(myCat.Name);
myCat.Speak(); // Outputs: The cat meows.
// Demonstrating polymorphism
Animal myAnimal1 = new Dog();
Animal myAnimal2 = new Cat();
myAnimal1.Speak(); // Outputs: The dog barks.
myAnimal2.Speak(); // Outputs: The cat meows.
}
}
}