← Back to C# Course | Chapter 7: Inheritance | Lesson 1 of 6

Inheritance की Basics

Inheritance किसी नई class को किसी पुरानी class की हर चीज़ पाने देता है, जैसे कोई बच्चा eye color inherit करता है। नई class फिर अपने खुद के extras जोड़ सकती है।

In this page:

  1. Inheritance Basics
Syntax
csharp
class BaseClass
{
    public void MethodName() { }
}

class DerivedClass : BaseClass
{
    // inherits MethodName and adds its own members
}

Inheritance Basics

Inheritance किसी class (derived class) को : syntax का उपयोग करते हुए किसी दूसरी class (base class) के fields और methods reuse और extend करने देता है। Derived class अपने base से public और protected हर चीज़ अपने आप पा लेती है।

यह "is-a" संबंधों को model करता है, जैसे एक Dog एक Animal होना।

Note: C# classes के लिए सिर्फ single inheritance को support करता है — एक class सिर्फ एक base class से inherit कर सकती है।

उदाहरण: Inheritance Basics

markup
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();
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी sealed class से inherit करना, जो एक compile error है।
  2. एक से ज़्यादा classes से inherit करने की कोशिश करना, क्योंकि C# single class inheritance support करता है।
  3. असंबंधित classes के लिए inheritance उपयोग करना बजाय एक is-a संबंध के।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.