Private Methods in Inheritance in OOP in JavaScript
Private methods are not inherited. This is done on purpose, so as not to violate encapsulation. Let's look at an example. Let's say we have the following parent class with a private method:
javascriptclass User {
setName(name) {
this.name = name;
}
getName() {
return this.#capeFirst(this.name);
}
#capeFirst(str) {
return str[0].toUpperCase() + str.slice(1);
}
}
Let the following class inherit from the parent class:
javascriptclass Student extends User {
setSurn(surn) {
this.surn = surn;
}
getSurn() {
return this.surn;
}
}
Let's say a child wants to use a private method of the parent. JavaScript will not allow this and will throw an error:
javascriptclass Student extends User {
setSurn(surn) {
this.surn = surn;
}
getSurn() {
return this.#capeFirst(this.surn); // there will be an error
}
}
Задание 1
Try using the private method of the parent in the Employee class.