Appearance
Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows you to create new classes based on existing classes. The new class inherits properties and methods from the base class, enabling code reuse and establishing relationships between classes.
Basic Inheritance
When a class inherits from another class, it can access the base class's public and protected members. The derived class can also override virtual methods to provide its own implementation.
csharp
public class Animal
{
public string Name { get; set; }
public virtual void MakeSound()
{
Console.WriteLine("Some sound");
}
}
public class Dog : Animal
{
public override void MakeSound()
{
Console.WriteLine("Woof!");
}
}
Base Class Constructor
When creating an instance of a derived class, the base class constructor is called first. You can explicitly call a base class constructor using the base keyword.
csharp
public class Animal
{
public Animal(string name)
{
Name = name;
}
}
public class Dog : Animal
{
public Dog(string name) : base(name)
{
}
}
Protected Members
Protected members are accessible within the same class and by derived classes, but not from outside the class hierarchy. This provides a way to share implementation details with derived classes while maintaining encapsulation.
csharp
public class Animal
{
protected string species; // Accessible in derived classes
protected virtual void Sleep()
{
Console.WriteLine("Sleeping...");
}
}