Protected and Abstract Classes
Explore how to use protected and abstract classes in TypeScript to control access to properties and methods within class hierarchies. Understand how protected members allow derived classes to access certain properties while keeping them hidden outside. Discover how abstract classes serve as blueprints for other classes, enabling shared properties and methods in your TypeScript projects.
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:
-
We define a class named
BaseClassProtectedfrom lines 2–13 that has a protected property namedidof typenumberand a private property namednameof typestring. We are setting the value of theprotectedidproperty within the constructor. -
We then define a class named
AccessProtectedfrom lines 16–27 that derives from the ...