We use base and derived classes to organize code by sharing common features and adding new ones. It helps avoid repeating code and makes programs easier to understand.
0
0
Base class and derived class in C Sharp (C#)
Introduction
When you have different types of animals that share common traits but also have unique behaviors.
When creating a game with various characters that share basic actions but have special abilities.
When building a system with different types of employees who all have names and IDs but different roles.
When you want to reuse code for shapes like circles and rectangles that all have an area but calculate it differently.
Syntax
C Sharp (C#)
class BaseClass { // common properties and methods } class DerivedClass : BaseClass { // additional properties and methods }
The base class is the parent that holds shared code.
The derived class inherits from the base and can add or change features.
Examples
Animal is the base class with a method Eat(). Dog is the derived class that adds Bark().
C Sharp (C#)
class Animal { public void Eat() { Console.WriteLine("Eating food"); } } class Dog : Animal { public void Bark() { Console.WriteLine("Barking"); } }
Vehicle is the base class. Car inherits Start() and adds Honk().
C Sharp (C#)
class Vehicle { public void Start() { Console.WriteLine("Starting vehicle"); } } class Car : Vehicle { public void Honk() { Console.WriteLine("Honking horn"); } }
Sample Program
This program shows a Dog class inheriting from Animal. Dog can use Eat() from Animal and also Bark() on its own.
C Sharp (C#)
using System; class Animal { public void Eat() { Console.WriteLine("Animal is eating"); } } class Dog : Animal { public void Bark() { Console.WriteLine("Dog is barking"); } } class Program { static void Main() { Dog myDog = new Dog(); myDog.Eat(); // inherited from Animal myDog.Bark(); // own method } }
OutputSuccess
Important Notes
Derived classes get all public and protected members from the base class automatically.
You can create many derived classes from one base class to share common code.
Use inheritance to keep code clean and avoid repeating the same code in multiple places.
Summary
Base class holds shared code for other classes.
Derived class inherits from base and can add or change features.
This helps organize code and reuse common parts easily.