Inheritance Basics
In this page:
Inheritance Basics
Inheritance lets a class (the derived class) reuse and extend the fields and methods of another class (the base class) using the : syntax. The derived class automatically gets everything public and protected from its base. This models "is-a" relationships, like a Dog being an Animal.
Note: C# only supports single inheritance for classes — a class can inherit from just one base class.
Example: Inheritance Basics
using System;
class Animal
{
public string Name;
public void Eat()
{
Console.WriteLine($"{Name} is eating");
}
}
class Dog : Animal
{
public void Bark()
{
Console.WriteLine($"{Name} says Woof!");
}
}
class Program
{
static void Main(string[] args)
{
Dog d = new Dog { Name = "Rex" };
d.Eat();
d.Bark();
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: