Inheritance की जानकारी
In this page:
class Child extends Parent {
constructor(param: type) {
super(param);
}
}
Basic Inheritance
एक derived class extends उपयोग करके एक base class से inherit करती है, और derived class को base class के public और protected members तक access अपने आप मिल जाता है उन्हें फिर से declare किए बिना।
उदाहरण: Basic Inheritance
class Animal {
eat() { console.log("Eating"); }
}
class Dog extends Animal {
bark() { console.log("Barking"); }
}
const dog = new Dog();
dog.eat();
dog.bark();
Inherited Properties
एक derived class अपनी visibility के according base class द्वारा declared properties उपयोग कर सकती है — public और protected members inherited और usable हैं, जबकि private members सिर्फ base class तक locked रहते हैं।
उदाहरण: Inherited Properties
class Animal {
public name: string = "Animal";
protected sound: string = "...";
}
class Dog extends Animal {
describe() {
console.log(this.name, this.sound);
}
}
new Dog().describe();
Base Constructor Call करना
जब एक derived class अपना खुद का constructor define करती है, इसे this access करने से पहले super(...) से base class constructor call करना चाहिए, यह ensure करते हुए कि object का inherited हिस्सा पहले पूरी तरह initialize हो।
उदाहरण: Calling the Base Constructor
class Animal {
constructor(public name: string) {}
}
class Dog extends Animal {
constructor(name: string, public breed: string) {
super(name);
}
}
const d = new Dog("Rex", "Labrador");
console.log(d.name, d.breed);
Method Overriding
एक derived class एक inherited method की अपनी implementation दे सकती है; override keyword इस intent को explicitly document करता है और compiler को mistakes पकड़ने देता है, जैसे method name गलत spell करना जो असल में कुछ override करने में fail होता है।
उदाहरण: Method Overriding
class Animal {
speak() { console.log("..."); }
}
class Dog extends Animal {
override speak() { console.log("Woof"); }
}
new Dog().speak();
Inheritance के Benefits
Inheritance repeated code घटाता है और related types के बीच असली relationships model करता है, जैसे एक Manager class जो Employee से extend करती है, लेकिन इसका उपयोग सिर्फ तब किया जाना चाहिए जब classes के बीच एक genuine is-a relationship मौजूद हो।
उदाहरण: Benefits of Inheritance
class Employee {
constructor(public name: string) {}
}
class Manager extends Employee {
manageTeam() { console.log(`${this.name} manages the team`); }
}
new Manager("Riya").manageTeam();
- एक derived constructor में this उपयोग करने से पहले
super(...)call करना भूल जाना, जो एक compile error है। - subclass से एक
privatebase member पढ़ने की कोशिश करना, जब access के लिए सिर्फpublicऔरprotectedmembers ही inherited होते हैं। - एक method को एक incompatible signature के साथ override करना, जैसे एक अलग parameter type या return type, जो base-class contract तोड़ता है।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: