CodeBlanks Logo Icon CodeBlanks

Summary - Advanced classes

Write a shape hierarchy with abstract class and interface.

Summary - Advanced classes

In this group you learned abstract classes, applying interfaces with implements, and getter/setter accessors. abstract class creates a base class; implements applies an interface contract to a class; get and set provide controlled access to properties.

abstract class Shape {
  abstract area(): number;
}
class Square extends Shape implements Drawable {
  get name() { return "square"; }
  area() { return 4 * 4; }
  draw() {}
}

Practice Write the Sekil hierarchy

Define abstract class Sekil with abstract alan(): number. Define interface Cizilebilir with ciz(): void. Make Kare extend Sekil, implement Cizilebilir, take a kenar parameter, have alan return kenar * kenar, and ciz print "kare çizildi". In the last line print new Kare(3).alan().

Starter code

index.ts
// Sekil adinda abstract sinif: alan metodu number donsun
// Cizilebilir adinda interface: ciz metodu void donsun
// Kare sinifi Sekil'i genişletip Cizilebilir'i uygulasin
// alan kenar*kenar donsun, ciz "kare çizildi" yazsin

// console.log(new Kare(3).alan());

Sample solution

index.ts
abstract class Sekil {
  abstract alan(): number;
}
interface Cizilebilir {
  ciz(): void;
}
class Kare extends Sekil implements Cizilebilir {
  kenar: number;
  constructor(kenar: number) { super(); this.kenar = kenar; }
  alan(): number { return this.kenar * this.kenar; }
  ciz(): void { console.log("kare çizildi"); }
}
console.log(new Kare(3).alan());

Expected output

9

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How to write a class that both inherits from a base class and implements an interface?

  • class X abstract B implements I
  • class X extends B, I
  • class X extends B implements I Correct answer
  • class X implements I extends B

Explanation: In TypeScript you write extends with the base class first, then implements with the interface; both can be in the same class.

2 Setter keyword

Question
class Kasa {
  private _para = 0;
  ____ para(v: number) { this._para = v; }
}
Answer
class Kasa {
  private _para = 0;
  set para(v: number) { this._para = v; }
}

Explanation: The accessor that runs when a value is assigned to a property is defined with the `set` keyword.

3 Advanced class concepts

Term Meaning
abstract Base class marker
implements Interface contract
get Read accessor
extends Inheritance

All lessons in Intermediate