📖 Scenario: Imagine you are creating a simple Car class to manage car details. Some information should be open for everyone to see, some should be hidden inside the car, and some should be visible only to the car and its close family (subclasses).
🎯 Goal: You will build a Car class using public, private, and protected access modifiers. Then you will create a subclass ElectricCar to see how protected members work.
📋 What You'll Learn
Create a Car class with public, private, and protected properties
Add a constructor to initialize the properties
Create a subclass ElectricCar that extends Car
Access the protected property inside the subclass
Print the public property from an instance
Try to access private and protected properties outside the class to see errors (commented out)
💡 Why This Matters
🌍 Real World
Access modifiers help protect sensitive data in software, like hiding engine numbers or internal details of a car from outside code.
💼 Career
Understanding access modifiers is important for writing secure and maintainable code in many programming jobs, especially when working with object-oriented languages like TypeScript.
Progress0 / 4 steps
1
Create the Car class with properties
Create a class called Car with these properties: public brand: string, private engineNumber: string, and protected mileage: number. Add a constructor that takes brand, engineNumber, and mileage as parameters and sets the properties.
Typescript
Hint
Use public, private, and protected keywords before the property names inside the class.
2
Create the ElectricCar subclass
Create a class called ElectricCar that extends Car. Add a constructor that takes brand, engineNumber, mileage, and batteryCapacity (number). Call the parent constructor with brand, engineNumber, and mileage. Add a public batteryCapacity: number property and set it.
Typescript
Hint
Use extends Car to create the subclass and super(...) to call the parent constructor.
3
Access protected property inside subclass
Inside the ElectricCar class, add a method called showMileage that returns a string showing the mileage using the protected property mileage. Use return `Mileage is ${this.mileage} km`; inside the method.
Typescript
Hint
Use this.mileage inside the method to access the protected property.
4
Create instance and print public property
Create an instance called myElectricCar of ElectricCar with brand 'Tesla', engineNumber 'E12345', mileage 15000, and batteryCapacity 85. Print the brand using console.log(myElectricCar.brand). Also print the mileage by calling console.log(myElectricCar.showMileage()). Comment out lines that try to access engineNumber or mileage directly from myElectricCar because they cause errors.
Typescript
Hint
Use new ElectricCar(...) to create the instance and console.log to print the values. Comment out direct access to private and protected properties.
Practice
(1/5)
1. Which access modifier in TypeScript allows a class member to be accessed from anywhere, including outside the class?
easy
A. private
B. public
C. protected
D. readonly
Solution
Step 1: Understand access modifiers
public means anyone can access the member, private restricts access to the class only, and protected allows access to the class and its subclasses.
Step 2: Identify the modifier allowing access from anywhere
Only public allows access from outside the class, including other classes and code.
Final Answer:
public -> Option B
Quick Check:
public = accessible everywhere [OK]
Hint: Public means open to all, private is class-only [OK]
Common Mistakes:
Confusing private with public access
Thinking protected is accessible outside class
Assuming readonly controls access
2. Which of the following is the correct syntax to declare a private property named age in a TypeScript class?
Access modifiers come before the property name and type, e.g., private age: number;.
Step 2: Identify correct modifier placement
private age: number; correctly places private before the property name and type. age: private number; has incorrect order.
Final Answer:
private age: number; -> Option A
Quick Check:
Modifier before name and type [OK]
Hint: Modifier comes before property name and type [OK]
Common Mistakes:
Placing modifier after property name
Using invalid syntax like 'age: private number;'
Confusing protected and private keywords
3. What will be the output of the following TypeScript code?
class Animal {
protected sound = 'Roar';
}
class Lion extends Animal {
public makeSound() {
return this.sound;
}
}
const lion = new Lion();
console.log(lion.makeSound());
medium
A. Error: Cannot access protected property
B. undefined
C. "Roar"
D. Error: Property 'sound' is private
Solution
Step 1: Understand protected access
The property sound is protected, so it can be accessed inside the class and its subclasses like Lion.
Step 2: Trace method call and output
The makeSound method returns this.sound, which is "Roar". So, console.log prints "Roar".
Final Answer:
"Roar" -> Option C
Quick Check:
Protected allows subclass access [OK]
Hint: Protected allows subclass access, so value is returned [OK]
Common Mistakes:
Thinking protected is inaccessible outside class
Confusing private with protected
Expecting runtime error for protected access
4. Identify the error in the following TypeScript code:
class Person {
private name: string = 'Alice';
}
const p = new Person();
console.log(p.name);
medium
A. Error: Property 'name' is protected, not accessible
B. No error, prints 'Alice'
C. Syntax error: missing constructor
D. Error: Cannot access private property 'name' outside class
Solution
Step 1: Check access modifier usage
The property name is declared private, so it cannot be accessed outside the class Person.
Step 2: Analyze the console.log statement
Trying to access p.name outside the class causes a compile-time error about private access.
Final Answer:
Error: Cannot access private property 'name' outside class -> Option D
Quick Check:
Private blocks outside access [OK]
Hint: Private blocks outside class access, causing error [OK]
Common Mistakes:
Assuming private properties are accessible outside
Confusing private with protected
Expecting code to print property value
5. Given the following TypeScript classes, which line will cause a compilation error?
class Vehicle {
protected speed: number = 0;
private engineOn: boolean = false;
public start() {
this.engineOn = true;
}
}
class Car extends Vehicle {
public accelerate() {
this.speed += 10; // Line 1
this.engineOn = true; // Line 2
}
}
const car = new Car();
car.accelerate();
hard
A. Line 2: Accessing private property 'engineOn' in subclass
B. No error, both lines are valid
C. Line 1: Accessing protected property 'speed' in subclass
D. Error at car.accelerate() call
Solution
Step 1: Understand access levels of properties
speed is protected, so accessible in subclass Car. engineOn is private, accessible only inside Vehicle.
Step 2: Analyze lines in subclass method
Line 1 accesses speed and is valid. Line 2 tries to access engineOn directly, which causes a compilation error.
Final Answer:
Line 2: Accessing private property 'engineOn' in subclass -> Option A
Quick Check:
Private blocks subclass access [OK]
Hint: Private blocks subclass access; protected allows it [OK]
Common Mistakes:
Assuming private is accessible in subclasses
Thinking protected is private
Ignoring error on private property access
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.