CodeBlanks Logo Icon CodeBlanks

abstract class

Learn abstract classes.

What is an abstract class?

A class marked abstract cannot be instantiated directly; it only serves as a base class for subclasses. Subclasses inherit from it with extends. abstract methods are declared without a body and must be implemented in the subclass.

abstract class Shape {
  abstract area(): number;
}
class Circle extends Shape {
  area() { return 3.14 * 2 * 2; }
}

Abstract method and concrete method

An abstract class can contain both abstract methods (no body, implemented in subclass) and concrete methods (have a body, inherited by subclass). The subclass must implement only abstract methods; concrete methods may be overridden optionally.

abstract class Animal {
  abstract makeSound(): void;
  introduce() { console.log("I am an animal"); }
}

Practice Compute square area

Define abstract class Sekil with abstract alan(): number inside. Then make Kare extend Sekil, take a kenar field, and implement alan returning kenar * kenar. Print new Kare(4).alan() with console.log.

Starter code

index.ts
// Sekil adinda abstract sinif tanimla
// abstract alan metodu number donsun
// Kare sinifi Sekil'i genişletsin
// alan metodunu kenar*kenar olarak uygula

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

Sample solution

index.ts
abstract class Sekil {
  abstract alan(): number;
}
class Kare extends Sekil {
  kenar: number;
  constructor(kenar: number) { super(); this.kenar = kenar; }
  alan(): number { return this.kenar * this.kenar; }
}
console.log(new Kare(4).alan());

Expected output

16

Questions and answers

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

1 Which of the following is true for an abstract class?

  • Can contain only static members
  • Cannot be instantiated directly with new Correct answer
  • Can have only one subclass
  • Methods cannot be defined inside it

Explanation: Abstract classes cannot be instantiated directly; subclasses inherit with extends and implement abstract methods.

2 Abstract class declaration

Question
 ____ class Sekil {
  abstract alan(): number;
}
Answer
 abstract class Sekil {
  abstract alan(): number;
}

Explanation: The `abstract` keyword is used to prevent direct instantiation and make the class a base class.

3 Abstract class parts

Term Meaning
abstract class Base class declaration
abstract metot Bodyless, implemented in subclass
extends Subclass inherits
somut metot Has body, inherited by subclass

All lessons in Intermediate