Inheritance
Learn about inheritance in OOP
Inheritance
What is inheritance?
Inheritance allows classes to acquire properties and methods from parent classes. Child classes can reuse parent code and add their own specialized behavior.
Benefits of inheritance?
- Reuse code from parent classes
- Create specialized versions of general classes
- Reduce code duplication
- Organize classes in hierarchies
- Share common functionality
// Parent class
class Character {
constructor(name, health) {
this.name = name;
this.health = health;
}
takeDamage(damage) {
this.health -= damage;
}
}
// Child class inherits from parent
class Guard extends Character {
constructor(name, health, weapon) {
super(name, health);
this.weapon = weapon;
}
}
const guard = new Guard("Guard", 100, "sword");
guard.takeDamage(10);
console.log(guard.name + " has " + guard.health + " health and weapon: " + guard.weapon);
What does this code do?
Characteris parent class with basic propertiesGuardextendsCharacterto inherit its methodsGuardadds its ownweaponpropertysuper()calls parent constructor- Child class reuses parent code while adding specialization
// More examples from collisions-mechanic
class Entity {
constructor(x, y) {
this.x = x;
this.y = y;
}
move(dx, dy) {
this.x += dx;
this.y += dy;
}
}
class Player extends Entity {
constructor(x, y, score) {
super(x, y);
this.score = score;
}
}
const player = new Player(100, 300, 0);
player.move(10, 0);
console.log(player.x); // 110
What does this code do?
Entityclass has common movement methodPlayerinheritsmove()from EntityPlayeradds its ownscoreproperty- Shows how child classes reuse parent functionality
- Demonstrates practical game hierarchy: generic entities with specialized versions
Try It Yourself
%%js // CODE_RUNNER: inheritence class Entity { constructor(x, y) { this.x = x; this.y = y; } } class Enemy extends Entity { constructor(x, y, type) { super(x, y); this.type = type; } } const goblin = new Enemy(100, 200, “Goblin”); console.log(goblin.type, goblin.x);