C# Inheritance
Objectives
- What is Inheritance ?
- Creating derived classes
- What is Base Classes and Derived Classes?
- Access modifiers (public, private, protected, internal)
What is Inheritance?
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a derived class or subclass) to inherit properties and behavior from another class (called a base class or superclass).
The derived class can reuse, extend, or modify the functionality of the base class, reducing code duplication and promoting code reuse.
Creating Derived Classes:
To create a derived class, you use the : symbol followed by the name of the base class.
The derived class inherits all the members (fields, properties, methods) of the base class and can define additional members or override existing ones.
public class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating.");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog is barking.");
}
}
What is Base Classes and Derived Classes ?
Base class is the class from which other classes (derived classes) inherit properties and behavior.
Derived class is a class that inherits from another class (base class) and can extend or modify its functionality.
Example:
Below is example that Animal is the base class, and Dog is the derived class.
public class Animal
{
public void Eat()
{
Console.WriteLine("Animal is eating.");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Dog is barking.");
}
}
Access Modifiers (public, private, protected, internal):
public : access modifier are accessible from any other class or assembly.
private : access modifier are accessible only within the same class.
protected : access modifier are accessible within the same class or derived classes.
internal : access modifier are accessible within the same assembly but not from outside.
Below example, the Eat, Move, and Run methods are accessible in the Dog class because they have public, protected, and internal access modifiers respectively.
public class Animal
{
public void Eat() {} // public method
private void Sleep() {} // private method
protected void Move() {} // protected method
internal void Run() {} // internal method
}
public class Dog : Animal
{
public void Play()
{
Eat(); // accessible (inherited from base class)
Move(); // accessible (inherited from base class)
Run(); // accessible (inherited from base class)
// Sleep(); // not accessible (private)
}
}