Abstract Methods in OOP in TypeScript
There are times when descendant classes need to have a common method, but the implementation of this method depends on a specific descendant. In this case, this method can be declared in the abstract class of the parent without writing its implementation. And then the descendants will be required to implement these methods. Such methods are called abstract and are also declared using the abstract keyword.
Let's take our abstract class User as an example. Let's say that the descendants of this class must necessarily have a method show, which displays the object's data.
The implementation of this method, however, will depend on the descendant. Let's declare this method abstract in the User class:
abstract class User {
public name: string;
constructor(name: string) {
this.name = name;
}
public abstract show(): string;
}
Let's implement this method in the descendant class Student:
class Student extends User {
public course: number;
constructor(name: string, course: number) {
super(name);
this.course = course;
}
show() {
return this.name + ' ' + this.course;
}
}
Let's implement this method in the descendant class Employee:
class Employee extends User {
public salary: number;
constructor(name: string, salary: number) {
super(name);
this.salary = salary;
}
show() {
return this.name + ' ' + this.salary;
}
}
In the abstract class Figure make abstract methods to get the area and perimeter.
In the descendant classes Square and Rectangle write the implementation of these methods.