You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classPerson{// full name is encapsulated as its a private memberprivate_fullName: string;publicfname: string;publiclname: string;publicconstructor(fname: string,lname: string){this.fname=fname;this.lname=lname;// encapsulate full name can only be updated by the class as its private// in this way full name will always be consistent with first & last namethis._fullName=`${this.fname}${this.lname}`;}// encapsulated full name is exposed through a public methodpublicgetFullName(): string{returnthis._fullName;}}constperson=newPerson('John','Smith');console.log('Person full name is',person.getFullName());
Advantages
Data protection
As per above example, the full name can't be mutated from outside as its a private member & internally derived from the class
Simpler maintenance
As per above example, we don't need to maintain the full name as the class does it.
Human error reduction
As per above example, as we are not computing the full name & the class is doing it on its own, hence a mistake in generating the full name is not possible if the first & last name are valid.
Abstraction
Example
classPerson{// full name is encapsulated as its a private memberprivate_fullName: string;publicfname: string;publiclname: string;publicconstructor(fname: string,lname: string){this.fname=fname;this.lname=lname;// encapsulate full name can only be updated by the class as its private// in this way full name will always be consistent with first & last namethis._fullName=`${this.fname}${this.lname}`;}// encapsulated full name is exposed through a public methodpublicgetFullName(): string{returnthis._fullName;}}constperson=newPerson('John','Smith');console.log('Person full name is',person.getFullName());