Create Objects with Classes
Create Objects with Classes
A class defines construction and methods for its instances. extends establishes an inheritance relationship, while super calls the parent constructor before the subclass uses this.
Before this topic, review Build Objects with Shorthand if its terms are unfamiliar.
What you’ll learn
- Explain create objects with classes through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: The inherited constructor stores the new name, and the inherited method returns it.
Work through the school example
This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · school.js · complete example
class Student {
constructor(name) {
this.name = name;
}
label() {
return this.name;
}
}
class Graduate extends Student {
}
console.log(new Graduate("Diya").label());
Expected output
DiyaRun in JavaScript compiler →What are Classes in JavaScript?
JavaScript classes are a syntactic sugar introduced in ES6 to write object-oriented code more cleanly. Under the hood, classes use prototypes, but they make the code easier to understand and maintain.
Defining a Class
A class is defined using the class keyword followed by a constructor and methods.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const john = new Person("John", 30);
john.greet();
Hello, my name is John and I am 30 years old.
How does the constructor work?
The constructor is a special method called automatically when a new object is created using the new keyword. It is used to initialize object properties.
Adding Methods to Classes
Any method defined inside the class (but outside the constructor) is added to the prototype of the object, making it memory-efficient.
Why use classes instead of functions?
Classes offer a more intuitive, object-oriented way to structure code—especially for beginners. They group constructor logic and behavior into a single block, improving readability and reuse.
Inheritance in JavaScript
Inheritance allows a class to acquire properties and methods from another class. This promotes code reuse and helps model real-world hierarchies.
Use the extends keyword to inherit from a parent class, and super() to call the parent class constructor.
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log("Some generic animal sound");
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // call to parent constructor
this.breed = breed;
}
makeSound() {
console.log("Woof! Woof!");
}
getDetails() {
console.log(`${this.name} is a ${this.breed}`);
}
}
const tommy = new Dog("Tommy", "Labrador");
tommy.makeSound();
tommy.getDetails();
Woof! Woof! Tommy is a Labrador
Q: What happens if you don't call super() in the child class?
A: You’ll get a reference error. The child class must call super() before accessing this keyword.
Example: Multiple Methods and Inheritance
Let’s take another real-world example where a Vehicle class is extended by Car class.
class Vehicle {
constructor(type) {
this.type = type;
}
startEngine() {
console.log(`${this.type} engine started.`);
}
}
class Car extends Vehicle {
constructor(type, brand) {
super(type);
this.brand = brand;
}
displayInfo() {
console.log(`This is a ${this.brand} ${this.type}.`);
}
}
const myCar = new Car("car", "Toyota");
myCar.startEngine();
myCar.displayInfo();
car engine started. This is a Toyota car.
Benefits of Using Classes and Inheritance
- Code Reuse: Share common logic through parent classes.
- Clear Structure: Logical grouping of behavior and state.
- Extensibility: Easily extend functionality without modifying existing code.
Quick Recap
- Use
classto define blueprints for objects. constructor()initializes object properties.- Use
extendsto inherit from another class. super()calls the parent class constructor.- Override methods by redefining them in the child class.
Test Your Understanding
Q: Can a subclass have its own methods along with inherited ones?
A: Yes, subclasses can define their own methods and also access or override methods from the parent class.
Q: Is class-based syntax mandatory in JavaScript?
A: No, but it’s the modern and recommended way to write object-oriented code over the older prototype-based approach.
Recognize the important boundary
Classes build on prototypes; they are not Java classes. Prefer composition when the relationship is has-a rather than is-a.
Connect instance methods to this and the method receiver, and compare inheritance with prototype property lookup.
Try a small variation
JavaScript · original source for practice
class Student {
constructor(name) {
this.name = name;
}
label() {
return this.name;
}
}
class Graduate extends Student {
}
console.log(new Graduate("Diya").label());
Your task: Replace 'Diya' with 'Saira'. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
The inherited constructor stores the new name, and the inherited method returns it.
JavaScript · complete worked variation
class Student {
constructor(name) {
this.name = name;
}
label() {
return this.name;
}
}
class Graduate extends Student {
}
console.log(new Graduate("Saira").label());
Expected output
SairaRun in JavaScript compiler →Predict the original program
JavaScript · original program for this question
class Student {
constructor(name) {
this.name = name;
}
label() {
return this.name;
}
}
class Graduate extends Student {
}
console.log(new Graduate("Diya").label());
Keep the useful idea
A class defines construction and methods for its instances. extends establishes an inheritance relationship, while super calls the parent constructor before the subclass uses this.
Check your variation against this explanation: The inherited constructor stores the new name, and the inherited method returns it.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.