0
0
Typescriptprogramming~10 mins

Access modifiers public private protected in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to make the property accessible from anywhere.

Typescript
class Car {
  [1] speed: number;
  constructor(speed: number) {
    this.speed = speed;
  }
}
Drag options to blanks, or click blank then click option'
Apublic
Bprivate
Cprotected
Dreadonly
Attempts:
3 left
💡 Hint
Common Mistakes
Using private or protected which restrict access.
Using readonly which only prevents modification but does not control access.
2fill in blank
medium

Complete the code to restrict access to the property only within the class.

Typescript
class BankAccount {
  [1] balance: number;
  constructor(balance: number) {
    this.balance = balance;
  }
}
Drag options to blanks, or click blank then click option'
Apublic
Bprivate
Cprotected
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using public which allows access everywhere.
Using protected which allows access in subclasses.
3fill in blank
hard

Fix the error in the code by choosing the correct access modifier for the property to allow subclass access but not outside access.

Typescript
class Animal {
  [1] sound: string;
  constructor(sound: string) {
    this.sound = sound;
  }
}

class Dog extends Animal {
  makeSound() {
    return this.sound;
  }
}
Drag options to blanks, or click blank then click option'
Aprivate
Bpublic
Cprotected
Dreadonly
Attempts:
3 left
💡 Hint
Common Mistakes
Using private which blocks subclass access.
Using public which allows access everywhere.
4fill in blank
hard

Fill both blanks to create a class with a private property and a public method to access it.

Typescript
class User {
  [1] password: string;
  constructor(password: string) {
    this.password = password;
  }
  [2] getPassword() {
    return this.password;
  }
}
Drag options to blanks, or click blank then click option'
Aprivate
Bpublic
Cprotected
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Making the method private so it cannot be called.
Making the property public exposing sensitive data.
5fill in blank
hard

Fill all three blanks to define a class with a protected property, a public method to get it, and a subclass accessing it.

Typescript
class Vehicle {
  [1] model: string;
  constructor(model: string) {
    this.model = model;
  }
  [2] getModel() {
    return this.model;
  }
}

class Car extends Vehicle {
  showModel() {
    return this.[3];
  }
}
Drag options to blanks, or click blank then click option'
Aprotected
Bpublic
Cmodel
Dprivate
Attempts:
3 left
💡 Hint
Common Mistakes
Using private property which blocks subclass access.
Using wrong property name in subclass.
Making method private so it cannot be called.