3. Access Modifiers Flashcards
What are the three major access modifiers that help with encapsulation in TypeScript?
private
, protected
, and public
.
What does the private
access modifier do?
It makes a member accessible only within the class to which it belongs.
What does the protected
access modifier do?
It makes a member accessible only within the class to which it belongs and the classes that derive from it.
What does the public
access modifier do?
It makes a member accessible from anywhere where the class itself is accessible.
Where is an access modifier written?
In front of a class member.
How do the default access modifiers differ from TypeScript to C#?
For the former, the default access modifier is public, whereas, for the latter, it is private.
What happens when a class that implements another overrides a protected member of the class it implements?
Compiler error. Protected members can only be accessed by child classes. Implementation doesn’t create child classes, extension does.
What does the static
access modifier do?
It makes a member accessible only through an invocation of the class itself, rather than an instance thereof.
How do you access the instance of a class from its static methods?
You can’t. Static methods don’t work with instances, and therefore there is no object in question.
How do you define a private static method?
You can’t. Static methods in TypeScript can only be public.
Is it possible to define two methods with the same name, one being static and the other an instance method, inside the same class?
Yes, because they are never going to be invoked in the same way.
What does the readonly
access modifier do?
It allows us to only read the value of a property, not modify it. It also disallows us to override it.
Can you set a read-only property from within its class’s constructor?
Yes. Yes, you can.