Access Modifiers in TypeScript Part-9

In our previous post we have overview about inheritance in Type Script.Today we will learn about access Modifiers.

Access Modifiers:

  • TypeScript have three type of access modifier which are public, private and protected.
  • Access Modifiers prevent to miss use of class members(functions and properties)
  • If no use any acess modifier,TypeScript set public access modifier to all class members(functions or properties) by defult

Public Access:

If use public access modifier with member of class(function or properties), Those members can be accessed anywhere in code freely.Like Base class or Sub Class.

Example:

Lets get code Explain:

All Public Member in class(functions and properties) have been called by object reference of SavingAccount class and public  member always call sub class.

Private Access:

If use private access modifier with member of class(function or properties), Those members can be accessed within self class by its other class members (functions) only.

Example:

Lets get code Explain:

When we call Amount properties which is private properties. Then we got error

privaterror

Above code we can see that Amount properties is used in TotalAmount Function which is in SavingAccount class. So we can easily use this Amount Properties.

protected Access:

If use protected access modifier with member of class (function or properties), Those members can be accessed within sub class. Otherwise this access modifier can not be accessed.

Example:

Base Clas

When we call Protected member of this class by using this class’s object then we got error

222222

Protected is like private.

Sub Class:

Above code we can see that Amount properties is using in TotalAmount function which is proptected and exist base class. From Above code we know that protected member is used within Sub class.Other wise we can not use this.

Happy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *