Classes & Interfaces — Series 2

Preview — 3 of 10 questions

javascript
class Animal {
  protected name: string;
  constructor(name: string) { this.name = name; }
}
class Dog extends Animal {
  bark(): string {
    return `${this.name} says woof`;
  }
}
const d = new Dog("Rex");
console.log(d.name);
ACompiles fine — protected allows access from anywhere, exactly like public
BCompile-time error on console.log(d.name) — protected allows access from within the declaring class and its subclasses, but not from external code; this.name inside Dog.bark() is fine because Dog extends Animal
CCompile-time error inside Dog.bark() — protected members aren't inherited by subclasses
DRuntime error: name is undefined when accessed from outside the class

javascript
class Counter {
  static count = 0;
  constructor() {
    Counter.count += 1;
  }
}
new Counter();
new Counter();
console.log(Counter.count);
const c = new Counter();
console.log(c.count);
ALogs 2 then 3 — static properties are shared across instances and also directly accessible on any instance
BLogs 0 then 0 — static properties don't actually persist across separate new calls
CCompile-time error on console.log(Counter.count) — static members can't be accessed through the class name
DLogs 2 correctly via Counter.count; c.count is a compile-time error — static members belong to the class itself, not to individual instances

javascript
class Temperature {
  private _celsius: number = 0;
  get fahrenheit(): number {
    return this._celsius * 9 / 5 + 32;
  }
  set fahrenheit(value: number) {
    this._celsius = (value - 32) * 5 / 9;
  }
}
const t = new Temperature();
t.fahrenheit = 212;
console.log(t.fahrenheit);
At.fahrenheit = 212 invokes the setter, and reading t.fahrenheit invokes the getter — both are accessed using plain property syntax even though they're backed by methods; the final log prints 212
BCompile-time error — fahrenheit is declared twice, once as a getter and once as a setter, which conflicts
Ct.fahrenheit = 212 compiles fine, but reading t.fahrenheit afterward returns undefined
DGetters and setters must be invoked as methods: t.fahrenheit() to read, and a separate setter call to write

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.