Object-oriented Programming (OOP) Concepts

 Object-oriented Programming (OOP) Concepts


JavaScript supports object-oriented programming concepts like classes, inheritance, and encapsulation.



class Person {

  constructor(name) {

    this.name = name;

  }


  sayHello() {

    console.log(`Hello, my name is ${this.name}.`);

  }

}


class Student extends Person {

  constructor(name, grade) {

    super(name);

    this.grade = grade;

  }


  sayHello() {

    super.sayHello();

    console.log(`I am in grade ${this.grade}.`);

  }

}


const john = new Student('John Doe', 8);

john.sayHello();

// Output:

// Hello, my name is John Doe.

// I am in grade 8.

In the example above, Person and Student are classes representing a person and a student, respectively. The Student class extends the Person class, inheriting its properties and methods. The sayHello() method is overridden in the Student class using the super keyword to call the parent class's implementation.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...