JavaScript Classes and Inheritance (ES6)
One of the most powerful features introduced in ES6 is the concept of classes. JavaScript is a prototype-based language, but with the introduction of class syntax, we now have a cleaner and more familiar way to implement object-oriented programming (OOP) patterns.
๐ What is a Class?
A class is a blueprint or template to create objects that share the same properties and behavior. Think of it as a mold from which multiple objects can be created.
Real-World Analogy: A “Car” class could have shared properties like brand, color, engine, and behaviors like accelerate() and brake(). Each specific car (Audi, BMW) is an object based on that class.
๐ก Features of Object-Oriented Programming
- Encapsulation: Bundling of data (variables) and methods (functions) together.
- Inheritance: Reuse of code by extending existing classes.
- Polymorphism: The ability to override methods in derived classes.
- Abstraction: Hiding complex logic and showing only essentials.
๐งฑ Declaring a Class in JavaScript (ES6)
JavaScript classes are declared using the class keyword. Every class has a special method called constructor(), which is automatically invoked when you create an object.
class Car {
constructor(carName, purchasedYear) {
this.carName = carName;
this.purchasedYear = purchasedYear;
}
run() {
return `Car is: ${this.carName}`;
}
}
const myCar = new Car("Audi", 2021);
console.log(myCar.run()); // Output: Car is: Audi
โ๏ธ Class vs Object
- Class: A template that defines properties and methods.
- Object: An actual instance created from a class.
๐ Example: Using a Class with constructor()
class Bike {
constructor(bikeName, launchYear) {
this.bikeName = bikeName;
this.launchYear = launchYear;
}
}
const myBike = new Bike("Bullet 250", 2018);
console.log(myBike.bikeName + " " + myBike.launchYear);
// Output: Bullet 250 2018
In this example, a class Bike is declared with two properties. We then create an object myBike using the new keyword and pass in values as arguments to the constructor.
๐งช Constructor vs Regular Method
class Laptop {
constructor(brand, year) {
this.brand = brand;
this.year = year;
}
details() {
return `Brand: ${this.brand}, Year: ${this.year}`;
}
}
const laptop1 = new Laptop("Dell", 2020);
console.log(laptop1.details());
constructor()is called only once when the object is created.- Other methods like
details()can be called any number of times.
๐ Assignment: Marks Calculation Using Class
Task: Write a program to enter 5 subjects’ marks and calculate total and percentage using a class.
class Marks {
constructor(sub1, sub2, sub3, sub4, sub5) {
this.sub1 = sub1;
this.sub2 = sub2;
this.sub3 = sub3;
this.sub4 = sub4;
this.sub5 = sub5;
}
total() {
return this.sub1 + this.sub2 + this.sub3 + this.sub4 + this.sub5;
}
percentage() {
return (this.total() / 500) * 100;
}
}
const student = new Marks(85, 90, 78, 92, 88);
console.log("Total Marks:", student.total());
console.log("Percentage:", student.percentage().toFixed(2) + "%");
๐งฌ Inheritance in ES6
ES6 allows one class to inherit properties and methods from another class using the extends keyword. To call the parent class’s constructor, we use the super() method.
class Animal {
constructor(legs) {
this.legs = legs;
}
walk() {
console.log(`Walking on ${this.legs} legs`);
}
}
class Bird extends Animal {
constructor(legs) {
super(legs); // Call the parent constructor
}
fly() {
console.log("Flying high!");
}
}
const sparrow = new Bird(2);
sparrow.walk(); // Output: Walking on 2 legs
sparrow.fly(); // Output: Flying high!
Explanation:
- The
Birdclass inherits fromAnimal. super(legs)calls the parent constructor to initialize the inherited property.- The object
sparrowhas access to bothwalk()andfly()methods.
๐ Assignments: Practice Classes and Inheritance
- Create a
Studentclass with properties for name, age, and course. Add a method to display full details. - Extend the
Studentclass into aHostellerclass that adds a property for hostelName. Include a method that prints both student and hostel details. - Create a class
BankAccountwith deposit and withdrawal methods. Then create a derived classSavingsAccountwith an interest method. - Write a class
Rectangleand a derived classSquare. Use inheritance to calculate area in both classes.
