...

/

Protected and Abstract Classes

Protected and Abstract Classes

Learn about the features of protected and abstract classes in TypeScript.

We'll cover the following...

Protected classes

Classes can mark both properties and functions with the protected keyword. If a property is marked as protected, then it is not accessible outside of the class itself, similar to the behavior of the private keyword.

It is, however, accessible to derived classes, which is different from private variables that are not accessible to derived classes, which can be seen in the following example:

// Define the BaseClassProtected class
class BaseClassProtected {
// Declare a protected property "id" of type number
protected id: number;
// Declare a private property "name" of type string with a default value of ""
private name: string = "";
// Constructor which takes a number argument "id"
constructor(id: number) {
// Set the value of the "id" property to the argument
this.id = id;
}
}
// Define the AccessProtected class which extends the BaseClassProtected class
class AccessProtected
extends BaseClassProtected {
// Constructor which takes a number argument "id"
constructor(id: number) {
// Call the constructor of the BaseClassProtected class with the argument
super(id);
// Log the value of the "id" property from the BaseClassProtected class
console.log(`base.id = ${this.id}`);
// Log the value of the "name" property from the BaseClassProtected class
console.log(`base.name = ${this.name}`);
}
}
Accessing protected properties
  • We define a class named BaseClassProtected from lines 2–13 that has a protected property named id of type number and a private property named name of type string. We are setting the value of the protected id property within the constructor.

  • We then define a class named AccessProtected from lines 16–27 that derives from the ...