Зміст курсу
C# Beyond Basics
C# Beyond Basics
Derived Classes
When we say a class is derived from another class, it means that it has all the fields and methods of the parent class and in addition to it, the derived class can contain additional fields and methods as well.
The syntax for making an inherited class is the following:
index
// Base class (parent class) public class BaseClass { // Fields and methods of the base class } // Derived class (child class) public class DerivedClass : BaseClass { // Additional fields and methods specific to the derived class }
Here's an example with some concrete code:
index
using System; // Base class (parent class) public class Animal { public string Name; public void Eat() { Console.WriteLine($"{Name} is eating."); } } // Derived class (child class) public class Dog : Animal { public void Bark() { Console.WriteLine($"{Name} is barking."); } } class ConsoleApp { static void Main() { // Creating an instance of the derived class Dog myDog = new Dog(); myDog.Name = "Buddy"; // Using inherited method from the base class myDog.Eat(); // Using method specific to the derived class myDog.Bark(); } }
In this example, Dog
is the derived class, inheriting from the Animal
base class. The Dog
class has access to the Name
property and the Eat
method from the Animal
class. Additionally, it introduces a new method, Bark
, which is specific to the Dog
class.
As illustrated in the diagram, there can be cases where a class inherits from a class which is already a class from some other:
index
using System; // Base class public class Animal { public void Eat() { Console.WriteLine("Animal is eating."); } } // Intermediate class inheriting from Animal public class Mammal : Animal { public void GiveBirth() { Console.WriteLine("Mammal is giving birth."); } } // Derived class inheriting from Mammal public class Dog : Mammal { public void Bark() { Console.WriteLine("Dog is barking."); } } class Program { static void Main() { Dog myDog = new Dog(); // Methods from the base class myDog.Eat(); // Methods from the intermediate class myDog.GiveBirth(); // Methods from the derived class myDog.Bark(); } }
In such a case, the class at the top-most level is called the Super Class. In this case Animal
is the super class. Such a case where where there are multiple levels of inheritence is called Multi-Level Inheritence.
Дякуємо за ваш відгук!