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 classclass BaseClassProtected {// Declare a protected property "id" of type numberprotected 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 argumentthis.id = id;}}// Define the AccessProtected class which extends the BaseClassProtected classclass AccessProtectedextends BaseClassProtected {// Constructor which takes a number argument "id"constructor(id: number) {// Call the constructor of the BaseClassProtected class with the argumentsuper(id);// Log the value of the "id" property from the BaseClassProtected classconsole.log(`base.id = ${this.id}`);// Log the value of the "name" property from the BaseClassProtected classconsole.log(`base.name = ${this.name}`);}}
-
We define a class named
BaseClassProtected
from lines 2–13 that has a protected property namedid
of typenumber
and a private property namedname
of typestring
. We are setting the value of theprotected
id
property within the constructor. -
We then define a class named
AccessProtected
from lines 16–27 that derives from the ...