TypeScript
Challenge 1: Classes
Solve a task combining classes and access modifiers.
Classes challenge
In this challenge you will solve tasks that combine classes, access modifiers (public, private, protected) and readonly fields. You learned to keep a class's internal state hidden while providing controlled access through accessor methods, and to build inheritance hierarchies with abstract classes. Now it is time to combine this knowledge.
Exercise Write a Bank class
Define a Banka class with a private _bakiye: number field. The constructor takes baslangic: number and assigns _bakiye. get bakiye(): number returns the value. set bakiye(v: number) sets to 0 if negative. yatir(m: number): void adds m to _bakiye. Create new Banka(100), deposit 50, print bakiye.
Show example solution
class Banka {
private _bakiye: number;
constructor(baslangic: number) { this._bakiye = baslangic; }
get bakiye(): number { return this._bakiye; }
set bakiye(v: number) { if (v < 0) this._bakiye = 0; else this._bakiye = v; }
yatir(m: number): void { this._bakiye += m; }
}
const b = new Banka(100);
b.yatir(50);
console.log(b.bakiye);
Exercise Shape hierarchy
Define abstract class Sekil with a protected renk: string field and constructor taking renk. Declare abstract alan(): number. goster(): void should print this.renk with console.log. Daire extends Sekil, takes private yaricap: number, constructor calls super(renk), alan() returns 3 * yaricap * yaricap. Create new Daire("kirmizi", 2) and call goster().
Show example solution
abstract class Sekil {
protected renk: string;
constructor(renk: string) { this.renk = renk; }
abstract alan(): number;
goster(): void { console.log(this.renk); }
}
class Daire extends Sekil {
private yaricap: number;
constructor(renk: string, yaricap: number) {
super(renk);
this.yaricap = yaricap;
}
alan(): number { return 3 * this.yaricap * this.yaricap; }
}
const d = new Daire("kirmizi", 2);
d.goster();
Test yourself
-
Which access modifier allows access only from within the class and its subclasses?
- private
- readonly
- protected
- public
Show answer
protected — protected members are accessible only within the class where they are defined and its subclasses; not from outside.
-
Protected access modifier
class Ust {
____ _gizli: string;
constructor(g: string) { this._gizli = g; }
}
class Alt extends Ust {
goster() { return this._gizli; }
}
Show answer
class Ust {
protected _gizli: string;
constructor(g: string) { this._gizli = g; }
}
class Alt extends Ust {
goster() { return this._gizli; }
}
-
Access modifiers
- private
- Only within the class
- protected
- Class and subclasses
- public
- From anywhere
- readonly
- Read-only
Next lesson: Challenge 2: Generics