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:
class User {
#name;
setName(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
Let the following child inherit from the parent:
class Student extends User {
}
Let's create a descendant object:
let student = new Student;
Let's use the parent's method to write its private property:
student.setName('john');
Let's use the parent's method to read its private property:
let name = student.getName();
console.log(name);
The following parent class is given:
class 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.
Create an object of class Employee and call the inherited setters and getters.
In the Employee class, create the following method:
getFull() {
return this.#name + ' ' + this.#surn;
}
Make sure the method code will result in an error.