Inheritance की Basics
Inheritance किसी नई class को किसी पुरानी class की हर चीज़ पाने देता है, जैसे कोई बच्चा eye color inherit करता है। नई class फिर अपने खुद के extras जोड़ सकती है।
In this page:
Syntax
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
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
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. #}
आम गलतियां
- किसी
sealedclass से inherit करना, जो एक compile error है। - एक से ज़्यादा classes से inherit करने की कोशिश करना, क्योंकि C# single class inheritance support करता है।
- असंबंधित classes के लिए inheritance उपयोग करना बजाय एक is-a संबंध के।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: