Saturday, November 10, 2018

TypeScript - Classes - public methods and access modifiers

Now the question arises, If i have declared private and protected properties in a class. How can we modify them? The answer is, we modify them using public methods of the class.

In the below example, we have a class City in which, we have 2 private properties:
  • type
  • elevation
Okay, elevation here is protected. But, remember, protected property is a private property. It has an additional feature that it can get inherited by a child class.

class City {
public name:string;
private type: string;
protected elevation: number;

constructor(name:string) {
this.name = name;
this.type = "city";
this.elevation = 505;
}

setElevation(elevation:number){
this.elevation = elevation;
console.log("new elevation = "+this.elevation);
}

getElevation(){
console.log(this.elevation);
}

setType(type:string){
this.type = type;
console.log("new type = "+this.type);
}

printType(){
console.log(this.type);
}

}

const city = new City("Hyderabad");
console.log(city);
city.getElevation();
city.setElevation(506);
city.printType();
city.setType("Metro");
city.printType();


To access these two private properties, we have created 4 public methods.
  • 2 methods for setting value
  • 2 methods for getting the value of these properties
The public methods created here are:
  • getElevation
  • setElevation
  • printType
  • setType
The set methods accept one argument here - which modifies the corresponding private properties.
The get methods enable us to retrieve the values contained in the private properties.

Let us compile the class:

$ tsc
$

Console Output:

City {name: "Hyderabad", type: "city", elevation: 505}
city-App.ts:104 505
city-App.ts:100 new elevation = 506
city-App.ts:113 city
city-App.ts:109 new type = Metro
city-App.ts:113 Metro

We can observe here - how the properties are affected using the set methods. Also, the output from the get methods are also visible in the Console.

No comments:

Post a Comment