JavaScript: Step 6- Classes and Inheritance

Classes and Inheritance are two key concepts in object-oriented programming that are used to create reusable code and simplify complex systems. In JavaScript, classes were introduced in ECMAScript 2015 (ES6) and provide a way to create objects with properties and methods.

  1. Classes:

A class is a blueprint for creating objects. It defines a set of properties and methods that the objects will have. Classes can be thought of as a template or a blueprint for creating objects.

Example program:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old`);
  }
}

let john = new Person("John", 30);
john.greet(); // Output: "Hello, my name is John and I'm 30 years old"

In the above example, we define a Person class with a constructor that takes two arguments: name and age. We also define a greet method that logs a message to the console. We then create a new Person object with the new keyword and call the greet method.

  1. Inheritance:

Inheritance is the process by which one class inherits properties and methods from another class. The class that is being inherited from is called the parent class or superclass, while the class that inherits from it is called the child class or subclass.

Example program:

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks`);
  }
}

let d = new Dog("Rufus");
d.speak(); // Output: "Rufus barks"

In the above example, we define an Animal class with a constructor that takes a name argument and a speak method that logs a message to the console. We then define a Dog class that extends the Animal class and overrides the speak method. We create a new Dog object and call the speak method.

By using classes and inheritance, we can create reusable and modular code that is easy to understand and maintain. Classes provide a way to encapsulate data and behavior into objects, while inheritance allows us to reuse code and create a hierarchy of related classes.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.