forked from Swap76/Learn-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolymorphism.js
More file actions
44 lines (34 loc) · 1.07 KB
/
Copy pathpolymorphism.js
File metadata and controls
44 lines (34 loc) · 1.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Polymorphism is one of the basic principles of object-oriented programming (OOP)
// It is the practice of designing objects to share behavior and be able to overwrite common behaviors associated with specific ones.
// First create the class Person
class Person {
constructor (name) {
this.name = name;
}
getName () {
return this.name;
}
getPosition () {
return "Unemployed";
}
}
// Extend the class Person with Employee
class Employee extends Person {
constructor (name, position, salary) {
super(name); // super() calls the constructor of Person
this.position = position;
this.salary = salary;
}
getPosition () { // overwrites the method of person
return this.position;
}
getSalary () {
return this.salary;
}
}
const person = new Person("James");
const employee = new Employee("Torsten", "Developer", 45000);
console.log(employee.getName()); // Output: Torsten
console.log(person.getName()); // Output: James
console.log(employee.getPosition()); // Output: Developer
console.log(person.getPosition()); // Output: Unemployed