Q1. What is inheritance in JavaScript?
Inheritance is a feature of Object-Oriented Programming that allows one class to inherit properties and methods from another class.
Inheritance helps in code reusability. Instead of writing the same code multiple times, a child class can reuse the functionality of a parent class.
Example
Inheritance helps in code reusability. Instead of writing the same code multiple times, a child class can reuse the functionality of a parent class.
Example
class Animal { eat() { return "Animal is eating"; }}
class Dog extends Animal {}
const dog = new Dog();console.log(dog.eat());Q2. Which keyword is used to implement inheritance in JavaScript?
The extends keyword is used to implement inheritance in JavaScript.
It allows a child class to inherit properties and methods from a parent class.
Example
It allows a child class to inherit properties and methods from a parent class.
Example
class Parent { show() { return "Parent method"; }}
class Child extends Parent {}
const obj = new Child();console.log(obj.show());Q3. What is a Parent Class and a Child Class?
A Parent Class (Base Class) is the class whose properties and methods are inherited.
A Child Class (Derived Class) is the class that inherits from another class.
The child class can use existing functionality from the parent class and can also add its own features.
A Child Class (Derived Class) is the class that inherits from another class.
The child class can use existing functionality from the parent class and can also add its own features.
Q4. What is the super keyword in inheritance?
The super keyword is used to call the constructor or methods of the parent class.
When a child class has its own constructor, it must call super() before using this.
Example
When a child class has its own constructor, it must call super() before using this.
Example
class Animal { constructor(name) { this.name = name; }}
class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; }}
const dog = new Dog("Tommy", "Labrador");console.log(dog.name);Q5. Why is Inheritance useful in JavaScript?
Inheritance is useful because it promotes code reusability and reduces duplication.
It allows developers to organize code in a structured and hierarchical way, making it easier to maintain and extend.
It allows developers to organize code in a structured and hierarchical way, making it easier to maintain and extend.
