C# OOP - Inheritance
Posted on June 28, 2024 (Last modified on October 11, 2024) • 1 min read • 202 wordsVideo is in Swedish
Inheritance in C# Object-Oriented Programming (OOP) is a mechanism of creating new classes from existing ones. It allows for code reusability and facilitates the creation of complex objects by building upon simpler ones.
The base class, also known as the parent or superclass, contains common attributes and methods that are shared among all derived classes. The derived class, also known as the child or subclass, inherits these properties and can add new ones or override existing ones to create a more specialized version of the base class.
In C#, inheritance is achieved using the class
keyword followed by the name of the base class in parentheses. For example:
public class Animal {
public void Eat() { Console.WriteLine("Eating"); }
}
public class Dog : Animal {
public void Bark() { Console.WriteLine("Woof!"); }
}
In this example, Dog
is a derived class that inherits from the base class Animal
. The Dog
class has its own method Bark()
in addition to the inherited Eat()
method.
Inheritance can be used for several purposes such as code reusability, creating complex objects by building upon simpler ones, and facilitating polymorphism. It is a powerful tool that allows developers to create more robust and maintainable software systems.
Swedish