JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows one class to inherit properties and methods from another. In JavaScript, inheritance enables new objects to take on the properties and methods of existing objects, making it easier to create and maintain scalable code.

Why We Need Inheritance?

Inheritance is crucial for several reasons:

  • Reusability: It allows developers to use existing code for new applications, reducing redundancy and errors.
  • Scalability: Easier maintenance and updates to the codebase as changes in the parent class automatically propagate to derived classes.
  • Organization: Helps in logically structuring code by generalizing shared behavior in base classes and specializing them in derived classes.

JavaScript Single Class Inheritance

Single class inheritance is where a class (derived or child class) inherits from only one class (base or parent class). This is the most common form of inheritance.

Example: Simple Single Class Inheritance

This example demonstrate basic single class inheritance in JavaScript by creating a parent class called Animal and a child class called Dog that inherits from Animal.

Image
Javascript
Javascript

. . . .

Explanation:

  • Parent Class - Animal:
    • constructor(name): This constructor takes name as an argument and sets it as the property of any instance of Animal. It initializes each new animal with a name.
    • speak(): This method outputs a generic message indicating the animal makes a noise. It accesses this.name to include the animal's name in the message.
  • Child Class - Dog:
    • extends Animal: The Dog class inherits from Animal, meaning it gains access to Animal's properties and methods.
    • bark(): Adds an additional method bark() that is specific to the Dog class. This method outputs a message indicating the dog barks, using this.name to reference the dog's name set by the Animal constructor.
  • Creating and Using an Instance of Dog:
    • const myDog = new Dog("Rover"): Creates a new instance of Dog named Rover. Because Dog extends Animal, the Animal constructor is automatically called to set Rover as the name.
    • myDog.speak(): Calls the inherited speak() method from the Animal class, which uses the name property set during the instantiation of Dog.
    • myDog.bark(): Calls the bark() method defined in the Dog class, demonstrating the additional behavior available to instances of Dog.

This example illustrates the fundamental concept of single class inheritance in JavaScript, showing how methods and properties can be inherited and used by child classes.

JavaScript super() Keyword

The super() keyword is used in derived classes to call the constructor of their parent class. This is necessary to ensure that the parent class is correctly initialized before the derived class adds its properties or alters behavior.

Example: Using the super() Keyword

Javascript
Javascript

. . . .

Explanation:

  • Cat Class: Extends Animal. The super(name) call in its constructor initializes the Animal part of Cat instances. The purr() method is specific to cats.
  • Using the Cat Class: Demonstrates that the Cat class inherits the speak() method from Animal and also defines its own purr() method, showing how super() is used to properly set up inheritance.

I apologize for missing the details in the instructions. Let's address the requirements for the hierarchical inheritance section properly this time, with clear and detailed explanations as well as comments in the code to ensure it's understandable for beginners.

JavaScript Hierarchical Inheritance

Image

Hierarchical inheritance is a powerful concept in object-oriented programming where multiple classes derive from a single base class. This approach is widely used to promote code reusability and logical organization.

For example, consider a software application for a vehicle management system. In such a system, a general class Vehicle might define attributes and behaviors common to all types of vehicles, such as speed and the ability to start or stop. Specific types of vehicles like Car, Truck, and Motorcycle could inherit these general traits from Vehicle while also introducing attributes unique to each vehicle type, such as trunk size for trucks or helmet presence for motorcycles.

This structured approach reduces redundancy and increases the clarity and maintainability of code.

Example: Hierarchical Inheritance

Javascript
Javascript

. . . .

Explanation:

  • Shape Class:
    • This class acts as the base class for all specific shapes. It includes a display() method which prints a generic message indicating that a shape is being displayed. This method is available to any class that inherits from Shape.
  • Circle Class:
    • Circle extends Shape, meaning it inherits the Shape class's methods and can also define its own methods. The draw() method in the Circle class prints a message specific to drawing circles, showing how derived classes can add or modify functionality.
  • Square Class:
    • Similarly, Square also extends Shape and includes its own draw() method tailored for squares. This demonstrates that different classes can inherit the same base functionality from Shape but still implement their specific behaviors.
  • Using the Classes:
    • Instances of both Circle and Square are created and used to call both the inherited display() method and their respective draw() methods. This illustrates how hierarchical inheritance allows classes to use generalized functionality from a base class while also defining their own specific behaviors.

JavaScript Multilevel Inheritance

Image

Multilevel inheritance allows for a class to inherit from another class that is already a derived class. This creates a chain of inheritance where properties and methods are passed down from the topmost base class to the lowest subclass.

In practical scenarios, this kind of inheritance can be seen in software frameworks where base functionalities are extended in multiple levels to add more specific features progressively. For instance, in a GUI application, a general Widget class could define basic display features, a Button class could extend Widget by adding button-specific functionalities, and a ToggleButton class could further refine the Button class with additional toggle behavior.

Example: Multilevel Inheritance

Javascript
Javascript

. . . .

Explanation:

  • Vehicle Class: Acts as the base class with a start() method that all vehicles can use.
  • Car Class: Inherits from Vehicle and adds playMusic(), enhancing the functionality for all cars.
  • ElectricCar Class: Further extends Car with a charge() method unique to electric vehicles, showcasing multilevel inheritance.
  • Using the Classes: The instance of ElectricCar demonstrates the use of inherited methods along the chain (from Vehicle and Car) plus its own method.

Inheriting Static Members of the Class

Static members of a class, including properties and methods, are shared across all instances of a class rather than being duplicated for each. Static members can also be inherited by subclasses, allowing them to use or override these shared resources. This feature is particularly useful in utility classes where a common set of functionalities needs to be available across various derived classes without instantiation.

For example, a MathUtility class might contain static methods for mathematical operations which could be inherited by more specialized utility classes.

Example: Inheriting Static Members

Javascript
Javascript

. . . .

Explanation:

  • Base Class: Contains a static method display() which is intended to be shared by all instances and subclasses of Base.
  • Derived Class: Inherits from Base. It does not redefine display(), so the method is accessed as defined in Base.
  • Static Method Usage: Derived.display() calls the inherited static method, showing that static methods belong not just to the instance of the class where they are defined but are accessible through the inheritance chain.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next