An abstract class is a base class that contains common implementation details that can be used by the derived class. An abstract class cannot be instantiated on its own.
To declare a class as abstract, we can use abstract
keyword followed by the class definition.
abstract class Animal {
}
We cannot instantiate an abstract class, for example, the below code will throw an error.
// NOT ALLOWED
let animal = new Animal(); // Cannot create an instance of an abstract class
If an abstract class contains abstract methods then it must be implemented by all the derived classes.
Suppose we want all the derived classes of the Animal class to have their own implementation of speak()
method, we can declare it as an abstract method.
abstract class Animal {
abstract speak(): void;
}
It is important to note that abstract methods do not have a body. Something like the one below is not allowed.
abstract class Animal {
abstract speak() { // Method 'speak' cannot have an implementation because it is marked abstract.
// NOT ALLOWED TO HAVE A BODY
}
}
The Typescript will complain, Method 'speak' cannot have an implementation because it is marked abstract.
Any class inheriting class Animal must contain a speak()
method of its own.
abstract class Animal {
abstract speak(): void;
}
class Dog extends Animal {
speak() {
console.log("Bow Bow");
}
}
let dog = new Dog();
dog.speak(); // Bow Bow
A class definition like below is not allowed because it does not contain speak()
method definition.
class Cat extends Animal {} // NOT ALLOWED
Typescript will complain, Non-abstract class 'Cat' does not implement inherited abstract member 'speak' from class 'Animal'.
We need to add the speak()
method to class Cat
.
class Cat extends Animal {
speak() {
console.log("Meow Meow");
}
}