protected
- TypeScript course
- Intermediate
- Lesson 8/89
- 4 min
Learn subclass access with protected.
What is protected?
protected indicates that a member is accessible inside the class itself and its subclasses (those that extends it). Like private, it is closed to the outside, but open to subclasses.
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Dog extends Animal {
bark(): string {
return this.name + " havlıyor";
}
}
const d = new Dog("Rex");
console.log(d.bark());private vs protected
private is accessible only in the class where it is defined; not even in subclasses. protected is accessible both in the defining class and in subclasses. From outside, both are closed.
class Base {
private secret: number = 1;
protected shared: number = 2;
}
class Child extends Base {
access(): number {
// this.secret; // error
return this.shared;
}
}Practice Write Animal and Dog classes
Define an Animal class with a protected name: string field and a constructor. Make Dog extends Animal and add a bark(): string method that returns this.name + " havlıyor". Create a new Dog("Rex") and call bark().
Starter code
// Animal sınıfı tanımla (korunan isim alanı, constructor ile al)
// Dog sınıfı Animal'ı genişletsin
// Dog'a bark metodu ekle, isim + " havlıyor" döndür
// yeni Dog oluştur, bark çağırSample solution
class Animal {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Dog extends Animal {
bark(): string {
return this.name + " havlıyor";
}
}
const d = new Dog("Rex");
console.log(d.bark());Expected output
Rex havlıyor
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Can a protected field be accessed from a subclass?
- Only from a static method
- No, not from anywhere
- Only from the same file
- Yes, accessible from a subclass Correct answer
Explanation: protected is accessible from the class itself and its subclasses (those that extend it). private is accessible only from the class itself; not from subclasses.
2 Complete the protected modifier
class Animal {
____ name: string;
}
class Animal {
protected name: string;
}
Explanation: You write protected because you want the name field to be accessible from subclasses too. public opens it to outside, private closes it to subclasses, and static moves it to the class level.
3 protected parts
| Term | Meaning |
|---|---|
protected |
Accessible from class and subclass |
extends Animal |
Subclass definition |
class Dog |
Subclass |
private |
Not accessible in subclass |