Classical Inheritance is a mechanism in which one class can extend the methods of another class.
Key Ideas:
Example (Java):
class Animal {
private name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
class Dog extends Animal {
}
Dog dog = new Dog("Rex");
Prototypal Inheritance is a mechanism in which an object (or a function constructor) can extend methods of another object. Every object has a prototype which is a link the parent object, this structure is called prototype chain.
Key ideas:
Example (JavaScript):
function Animal(name) {
this.name = name;
}
Animal.prototype.getName() {
return this.name;
}
funciton Dog(name) {
Animal.call(this, name);
}
Dog.prototype = Object.create(Animal.prototype);
const dog = new Dog("Rex");
In ES6 class keyword was added which allows to use the syntax similar to other C-like languages. But under the hood JavaScript supports only prototyple inheritance, so the example below works almost identical to example above.
Example:
class Animal {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class Dog extends Animal {
}
const dog = new Dog("Rex");