Typescript Access Modifiers: Aim:-Write A Program To Implement Access Modifier Using Typescript Theory
Typescript Access Modifiers: Aim:-Write A Program To Implement Access Modifier Using Typescript Theory
THEORY:-
Like other programming languages, Typescript allows us to use access modifiers at the class
level. It gives direct access control to the class member. These class members are functions and
properties. We can use class members inside its own class, anywhere outside the class, or within
its child or derived class.
The access modifier increases the security of the class members and prevents them from invalid
use. We can also use it to control the visibility of data members of a class. If the class does not
have to be set any access modifier, TypeScript automatically sets public access modifier to all
class members.
1. Public
2. Private
3. Protected
Public
In TypeScript by default, all the members (properties and methods) of a class are public. So,
there is no need to prefix members with this keyword. We can access this data member anywhere
without any restriction.
Private
The private access modifier cannot be accessible outside of its containing class. It ensures that
the class members are visible only to that class in which it is containing.
Protected
A Protected access modifier can be accessed only within the class and its subclass. We cannot
access it from the outside of a class in which it is containing.
SOURCECODE
class Student {
public studCode: number;
studName: string;
}
let stud = new Student();
stud.studCode = 101;
stud.studName = "Joe Root";
console.log(stud.studCode+ " "+stud.studName);
OUTPUT
class Student {
public studCode: number;
private studName: string;
constructor(code: number, name: string){
this.studCode = code;
this.studName = name;
}
public display() {
return (`My unique code: ${this.studCode}, my name: ${this.studName}.`);
}
}
let student: Student = new Student(1, "JoeRoot");
console.log(student.display());
OUTPUT
class Student {
public studCode: number;
protected studName: string;
constructor(code: number, name: string){
this.studCode = code;
this.studName = name;
}
}
class Person extends Student {
private department: string;
constructor(code: number, name: string, department: string) {
super(code, name);
this.department = department;
}
public getElevatorPitch() {
return (`My unique code: ${this.studCode}, my name: ${this.studName} and I am in $
{this.department} Branch.`);
}
}
let joeRoot: Person = new Person(1, "JoeRoot", "CS");
console.log(joeRoot.getElevatorPitch());
OUTPUT