Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Class Inheritance in JavaScript

Class Inheritance in JavaScript

? Class Inheritance in JavaScript

Inheritance allows one class (child) to inherit properties and methods from another class (parent), promoting code reuse and organization.


? Basic Syntax: ES6 Classes and Inheritance

// Parent classclass Animal {  constructor(name) {    this.name = name;  }  speak() {    console.log(`${this.name} makes a sound.`);  }}// Child class extends Animalclass Dog extends Animal {  constructor(name, breed) {    super(name);           // Call parent constructor    this.breed = breed;  }  speak() {    console.log(`${this.name} barks.`);  }}const dog = new Dog("Buddy", "Golden Retriever");dog.speak(); // Output: Buddy barks.

? Explanation

  • class Dog extends Animal — Dog inherits from Animal

  • super(name) — calls the constructor of the parent class

  • Child class can override parent methods (speak in example)

  • Child class can add new properties or methods


? More Features

1. Calling Parent Methods From Child

class Cat extends Animal {  speak() {    super.speak(); // Calls Animal's speak()    console.log(`${this.name} meows.`);  }}const cat = new Cat("Whiskers");cat.speak();// Output:// Whiskers makes a sound.// Whiskers meows.

2. Inheriting Without Adding Anything

class Bird extends Animal {}const bird = new Bird("Tweety");bird.speak();  // Tweety makes a sound.

? Why Use Class Inheritance?

  • Code reuse

  • Logical grouping of similar objects

  • Easier maintenance

  • Polymorphism (overriding methods)


?? Notes

  • JavaScript uses prototype-based inheritance under the hood.

  • ES6 class syntax is mostly syntactic sugar over prototypes.

  • You can also create inheritance using constructor functions and prototypes (older style).


If you want, I can also show you prototype-based inheritance or examples with multiple levels of inheritance. Just ask!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql