Private Properties in Inheritance in OOP in JavaScript
Private properties are not inherited. But the child can manipulate them through the parent's public methods. Let's see in practice. Let's have the following parent class with a private property and its getter and setter:
javascriptclass User {
#name;
setName(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
Let the following child inherit from the parent:
javascriptclass Student extends User {
}
Let's create a descendant object:
javascriptlet student = new Student;
Let's use the parent's method to write its private property:
javascriptstudent.setName('john');
Let's use the parent's method to read its private property:
javascriptlet name = student.getName();
console.log(name);
Задание 1
The following parent class is given:
javascriptclass User {
#name;
#surn;
setName(name) {
this.#name = name;
}
getName() {
return this.#name;
}
setSurn(surn) {
this.#surn = surn;
}
getSurn() {
return this.#surn;
}
}
Make a class Employee that inherits from this parent.
Задание 2
Create an object of class Employee and call the inherited setters and getters.
Задание 3
In the Employee class, create the following method:
javascriptgetFull() {
return this.#name + ' ' + this.#surn;
}
Make sure the method code will result in an error.