C# Inheritance
Inheritance lets one class take fields and methods from another class. The class that receives them can also add members of its own.
Inherited field and method
Dog inherits from Animal. The Dog object uses a field and a method from Animal.
using System;
class Animal
{
public string name = "Buddy";
public void Eat()
{
Console.WriteLine("The animal eats");
}
}
class Dog : Animal
{
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Console.WriteLine(dog.name);
dog.Eat();
}
}Dog adds a method
Dog adds a Bark method here. Animal has no such method.
using System;
class Animal
{
public void Eat()
{
Console.WriteLine("The animal eats");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Woof");
}
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
dog.Eat();
dog.Bark();
}
}Two classes share Eat
Dog and Cat both inherit from Animal. Both objects can call the Eat method from Animal.
using System;
class Animal
{
public void Eat()
{
Console.WriteLine("The animal eats");
}
}
class Dog : Animal
{
}
class Cat : Animal
{
}
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Cat cat = new Cat();
dog.Eat();
cat.Eat();
}
}Example
using System;
class Vehicle
{
public string brand = "Ford";
public void Drive()
{
Console.WriteLine("The vehicle drives");
}
}
class Car : Vehicle
{
public void Honk()
{
Console.WriteLine("Beep");
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Car();
Console.WriteLine(car.brand);
car.Drive();
car.Honk();
}
}Key points
- The base class is the class that gives its members.
- The derived class is the class that receives the members.
- Write class Dog : Animal to make Dog inherit from Animal.
- The colon in the class line names the base class.
- A derived class gains the public members of its base class.
- Code written once in the base class serves every derived class.
In this example, Car inherits from Vehicle. The brand field prints Ford from Vehicle. The Drive method also comes from Vehicle. Car adds its own Honk method, which prints Beep last.
Note
A class can inherit from only one base class.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
Which line makes Dog inherit from Animal?