Classes and Inheritance

Back

Loading concept...

🏗️ Classes & Inheritance: Building Your Own LEGO Factory!

Imagine you have a magical LEGO factory. This factory has a special blueprint that tells you exactly how to build specific toys. Every time you want a new toy, you follow the same blueprint—but you can make each toy a little different (different colors, different sizes).

That’s what a Class is in JavaScript! A class is like a blueprint for creating objects.


🎯 What You’ll Learn

graph TD A["🏭 Class Declaration"] --> B["🔧 Constructor Method"] B --> C["⚡ Instance Methods"] C --> D["📦 Instance Properties"] D --> E["🧬 extends Keyword"] E --> F["🦸 super Keyword"] F --> G["🔄 Method Overriding"] G --> H["🤔 Inheritance vs Composition"]

🏭 Class Declarations: The Blueprint

A class declaration is how you create your blueprint. It’s like writing down the instructions for your LEGO factory.

Simple Example

class Dog {
  // This is where the magic
  // instructions go!
}

What just happened?

  • class = The special word that says “I’m making a blueprint!”
  • Dog = The name of our blueprint (always starts with a Capital letter)
  • { } = The curly braces hold all our instructions

Real-Life Connection

Think of it like a recipe card:

  • 📝 Recipe Title = Class Name (Dog)
  • 📋 Recipe Instructions = What goes inside { }

🔧 Constructor Method: The Birth Certificate

When a baby is born, the hospital creates a birth certificate with the baby’s name, weight, and birthday. The constructor does the same thing for objects!

The constructor is a special method that runs automatically when you create a new object.

Simple Example

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

// Creating a new dog!
const buddy = new Dog("Buddy", 3);
console.log(buddy.name); // "Buddy"
console.log(buddy.age);  // 3

Breaking it down:

  • constructor = Special word meaning “run this when creating something new”
  • (name, age) = Information we need to create the object
  • this.name = name = Saving the name to THIS specific dog
  • new Dog("Buddy", 3) = Making a new dog using our blueprint!

The Magic Word: this

this is like saying “THIS specific object.”

Imagine 10 dogs in a room. When one dog says “my name is Buddy,” they’re talking about THEMSELVES, not the other dogs. this works the same way!


⚡ Instance Methods: Teaching Tricks

Instance methods are like tricks you teach your dog. Every dog created from your blueprint can do these tricks!

Simple Example

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

  bark() {
    console.log(this.name + " says: Woof!");
  }

  sit() {
    console.log(this.name + " sits down.");
  }
}

const buddy = new Dog("Buddy");
buddy.bark(); // "Buddy says: Woof!"
buddy.sit();  // "Buddy sits down."

What’s happening:

  • bark() and sit() are instance methods
  • They’re actions that every dog can perform
  • Each dog uses this.name to know ITS OWN name

Pro Tip 🚀

Methods are just functions that live inside a class. They don’t need the function keyword!


📦 Instance Properties: Personal Belongings

Instance properties are like each dog’s personal belongings. One dog might have a blue collar, another might have a red one.

Simple Example

class Dog {
  constructor(name, color) {
    // Instance properties
    this.name = name;
    this.collarColor = color;
    this.isHungry = true;
  }

  eat() {
    this.isHungry = false;
    console.log(this.name + " is full!");
  }
}

const buddy = new Dog("Buddy", "blue");
const max = new Dog("Max", "red");

console.log(buddy.collarColor); // "blue"
console.log(max.collarColor);   // "red"

Key Points:

  • Each dog has its OWN name, collarColor, and isHungry
  • Changing one dog’s properties doesn’t affect other dogs
  • Properties can be changed by methods (like eat() changes isHungry)

🧬 extends Keyword: Family Inheritance

Now here’s where it gets exciting! What if you want to create a special type of dog, like a SuperDog with powers?

The extends keyword lets you create a new class that inherits everything from a parent class, like children inherit traits from parents!

Simple Example

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

  eat() {
    console.log(this.name + " is eating.");
  }
}

// Dog EXTENDS Animal (inherits from it)
class Dog extends Animal {
  bark() {
    console.log("Woof woof!");
  }
}

const buddy = new Dog("Buddy");
buddy.eat();  // "Buddy is eating." (from Animal!)
buddy.bark(); // "Woof woof!" (Dog's own method)

The Magic:

  • Dog extends Animal = Dog gets EVERYTHING Animal has
  • Dog can also have its OWN special abilities (bark)
  • It’s like a child who inherits their parent’s eye color but also develops their own unique talents!
graph TD A["🐾 Animal"] -->|extends| B["🐕 Dog"] A -->|extends| C["🐱 Cat"] B --> D["Has: eat#40;#41; + bark#40;#41;"] C --> E["Has: eat#40;#41; + meow#40;#41;"]

🦸 super Keyword: Calling Your Parents

When a child class needs to use something from its parent, it calls super. It’s like calling your parents for help!

super in Constructor

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

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // Call parent's constructor!
    this.breed = breed;
  }
}

const buddy = new Dog("Buddy", "Golden Retriever");
console.log(buddy.name);  // "Buddy"
console.log(buddy.breed); // "Golden Retriever"

Important Rules:

  • In a child class, you MUST call super() BEFORE using this
  • super(name) sends the name to the parent’s constructor
  • Think of it as: “Hey Parent, please set up my name first!”

super in Methods

class Animal {
  speak() {
    console.log("Some sound...");
  }
}

class Dog extends Animal {
  speak() {
    super.speak(); // Call parent's speak()
    console.log("Woof!"); // Add extra behavior
  }
}

const buddy = new Dog();
buddy.speak();
// Output:
// "Some sound..."
// "Woof!"

🔄 Method Overriding: Be Your Own Dog!

Sometimes a child class wants to do things differently than the parent. This is called method overriding—replacing the parent’s method with your own version.

Simple Example

class Animal {
  speak() {
    console.log("The animal makes a sound");
  }
}

class Dog extends Animal {
  speak() {
    // Override the parent's method!
    console.log("The dog barks: Woof!");
  }
}

class Cat extends Animal {
  speak() {
    console.log("The cat meows: Meow!");
  }
}

const animal = new Animal();
const dog = new Dog();
const cat = new Cat();

animal.speak(); // "The animal makes a sound"
dog.speak();    // "The dog barks: Woof!"
cat.speak();    // "The cat meows: Meow!"

What’s Happening:

  • Animal has a basic speak() method
  • Dog overrides it with its own version
  • Cat overrides it with a different version
  • Same method name, but different behaviors!

Real-Life Analogy 🎨

It’s like inheriting your parent’s recipe for soup, but adding your own special ingredients to make it YOUR soup!


🤔 Inheritance vs Composition: Two Ways to Build

There are two main ways to build complex objects:

Inheritance: “IS-A” Relationship

A Dog IS AN Animal. Use extends.

class Animal { }
class Dog extends Animal { }
// Dog IS AN Animal

Composition: “HAS-A” Relationship

A Car HAS AN Engine. Use objects inside objects.

class Engine {
  start() {
    console.log("Vroom!");
  }
}

class Car {
  constructor() {
    // Car HAS an engine
    this.engine = new Engine();
  }

  drive() {
    this.engine.start();
    console.log("Car is moving!");
  }
}

const myCar = new Car();
myCar.drive();
// "Vroom!"
// "Car is moving!"

When to Use Which?

Inheritance Composition
Clear “is-a” relationship Mix-and-match abilities
Dog is an Animal Car has an Engine
Simple hierarchies More flexible
Share lots of code Swap parts easily

The Golden Rule 🌟

“Favor composition over inheritance” — This means: When in doubt, use composition! It’s more flexible and easier to change later.

Why Composition is Often Better

// With Composition (flexible!)
class Swimmer {
  swim() { console.log("Swimming!"); }
}

class Flyer {
  fly() { console.log("Flying!"); }
}

class Duck {
  constructor() {
    this.swimmer = new Swimmer();
    this.flyer = new Flyer();
  }

  swim() { this.swimmer.swim(); }
  fly() { this.flyer.fly(); }
}

// Duck can swim AND fly!
const donald = new Duck();
donald.swim(); // "Swimming!"
donald.fly();  // "Flying!"

🎉 Summary: Your Class Toolbox

graph TD A["📘 CLASS"] --> B["constructor: birth certificate"] A --> C["methods: tricks/actions"] A --> D["properties: belongings"] A --> E["extends: inherit from parent"] A --> F["super: call parent help"] A --> G["override: your own version"]
Concept What It Does Analogy
Class Declaration Creates a blueprint Recipe card
Constructor Sets up new objects Birth certificate
Instance Methods Actions objects can do Tricks your dog knows
Instance Properties Data each object owns Personal belongings
extends Inherits from parent Child inherits from parent
super Calls parent’s code Asking parents for help
Method Overriding Replace parent’s method Making the recipe your own
Composition Build with parts LEGO pieces combined

🚀 You Did It!

You now understand how to:

  • ✅ Create classes (blueprints for objects)
  • ✅ Use constructors (birth certificates)
  • ✅ Add methods (teach tricks)
  • ✅ Define properties (personal belongings)
  • ✅ Extend classes (family inheritance)
  • ✅ Use super (call your parents)
  • ✅ Override methods (be your own version)
  • ✅ Choose between inheritance and composition

You’re ready to build amazing things with JavaScript classes! 🎊

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.