Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows you to create new classes based on existing ones. A derived class, or subclass, inherits the members of its parent class, or base class, thereby enabling code reuse and extension of functionality.
In C#, you can create a derived class using the :
symbol followed by the name of the base class. The derived class inherits all the properties, methods, and other members of the base class.
Here's an example that demonstrates inheritance in C#:
1using System;
2
3// Base class
4public class Animal
5{
6 public string Name { get; set; }
7
8 // Method
9 public void Move()
10 {
11 Console.WriteLine(Name + " is moving.");
12 }
13}
14
15// Derived class
16public class Dog : Animal
17{
18 // Additional property
19 public string Breed { get; set; }
20
21 // Additional method
22 public void Bark()
23 {
24 Console.WriteLine("Woof woof!");
25 }
26}
27
28// Usage
29Dog myDog = new Dog()
30{
31 Name = "Buddy",
32 Breed = "Golden Retriever"
33};
34
35myDog.Move();
36myDog.Bark();
In this example, we define a base class Animal
with a property Name
and a method Move
. We then create a derived class Dog
that inherits from Animal
. The Dog
class has an additional property Breed
and an additional method Bark
.
We create an instance of the Dog
class called myDog
and set its Name
and Breed
properties. We can then call the Move
method inherited from the Animal
class and the Bark
method defined in the Dog
class.
Inheritance allows you to create a hierarchy of classes with increasing levels of specialization. It promotes code reuse, as you can define common behavior in a base class and extend it in derived classes. Understanding inheritance is essential for building complex object-oriented systems and implementing advanced programming concepts like polymorphism and encapsulation.
xxxxxxxxxx
myDog.Bark();
using System;
// Base class
public class Animal
{
public string Name { get; set; }
// Method
public void Move()
{
Console.WriteLine(Name + " is moving.");
}
}
// Derived class
public class Dog : Animal
{
// Additional property
public string Breed { get; set; }
// Additional method
public void Bark()
{
Console.WriteLine("Woof woof!");
}
}
// Usage
Dog myDog = new Dog()