Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Abstract Classes

TypeScript Abstract Classes

An abstract class (Abstract Class) is an important concept in TypeScript object-oriented programming.

It is a class that cannot be instantiated directly and can only serve as a base class for other classes to inherit from.

Abstract classes are mainly used to define common properties and methods for subclasses, providing a unified structure and behavior template.


Abstract class inheritance hierarchy abstract class Animal Cannot be instantiated directly class Dog extends Animal class Cat extends Animal Abstract class features abstract methods: must be implemented by subclasses Concrete methods: can be used directly by subclasses Can be used as a type: accepts subclass instances

Why abstract classes are needed

In object-oriented programming, we often need to define some base classes.

These base classes describe the properties and methods common to subclasses, but the implementation details of some methods are left to the subclasses to decide.

Abstract classes solve this problem: they let us define method signatures (declarations) while leaving the concrete implementation to the subclasses.

Concept explanation:An abstract class is a type somewhere between a regular class and an interface. It has features of an interface (defining method signatures) as well as features of a class (it can have concrete method implementations and constructors).


Abstract class basics

Use abstract The abstract keyword declares abstract classes and abstract methods.

An abstract class can contain abstract methods and concrete methods (methods with implementations).

Example

// Declare an abstract class using the abstract keyword

// An abstract class cannot be instantiated directly; it can only serve as a base class

abstract

class

Animal

{

   

// The animal's name property

    name

:

string

;

   

// Constructor

    constructor

(

name

:

string

)

{

       

this

.

name

=

name

;

   

}

   

// Abstract method: modified with abstract, has no method body

   

// Subclasses must implement this method

   

abstract

speak

(

)

:

void

;

   

// Concrete method: a method with a concrete implementation

   

// Subclasses can inherit and use it directly without overriding

    move

(

)

:

void

{

        console.

log

(

this

.

name

" is moving"

)

;

   

}

}

// Trying to instantiate an abstract class will cause an error

// var animal = new Animal("Animal"); // Error: cannot instantiate an abstract class

// Define the Dog class inheriting from Animal

class

Dog

extends

Animal

{

   

// The subclass must implement the parent's abstract method speak()

    speak

(

)

:

void

{

        console.

log

(

this

.

name

" Woof woof woof!"

)

;

   

}

}

// Create a Dog instance

var

dog

=

new

Dog

(

"Wangcai"

)

;

dog.

speak

(

)

;

 

// Call the method implemented by the subclass

dog.

move

(

)

;

 

// Inherit the parent's concrete method

Running result:

旺财 汪汪汪!

旺财 在移动

Explanation:An abstract method has no method body (only a method signature), and subclasses must implement it. A concrete method has a concrete implementation that subclasses can inherit and use directly.


Abstract method

An abstract method is a method declared but not implemented in an abstract class.

After a subclass inherits from an abstract class, it must implement all abstract methods, otherwise an error will occur.

Example

// Define the abstract class Shape

abstract

class

Shape

{

   

// Abstract method: declaration only, no implementation

   

// Subclasses must implement these two methods

   

abstract

area

(

)

:

number

;

   

abstract

perimeter

(

)

:

number

;

   

// Concrete method: can use abstract methods

   

// This method calls an abstract method; after inheritance, subclasses can use it normally

    describe

(

)

:

void

{

        console.

log

(

"Area: "

this

.

area

(

)

.

toFixed

(

2

)

)

;

   

}

}

// Define the Rectangle class inheriting from Shape

class

Rectangle

extends

Shape

{

   

// The rectangle's width

    width

:

number

;

   

// The rectangle's height

    height

:

number

;

   

// Constructor

    constructor

(

width

:

number

,

height

:

number

)

{

       

super

(

)

;

 

// Call the parent class constructor

       

this

.

width

=

width

;

       

this

.

height

=

height

;

   

}

   

// Implement the abstract method: calculate the area

    area

(

)

:

number

{

       

return

this

.

width

this

.

height

;

   

}

   

// Implement the abstract method: calculate the perimeter

    perimeter

(

)

:

number

{

       

return

2

(

this

.

width

this

.

height

)

;

   

}

}

// Create a Rectangle instance

var

rect

=

new

Rectangle

(

4

,

5

)

;

// Call the inherited describe method, which internally calls the subclass's area method

rect.

describe

(

)

;

console.

log

(

"Perimeter: "

rect.

perimeter

(

)

)

;

Running result:

面积: 20.00

周长: 18

Tip:A concrete method can call an abstract method. This is because when the concrete method is called, the subclass has already implemented the abstract method, so it can execute normally.


Abstract classes as types

Abstract classes can be used as parameter types.

This means a function can accept instances of any subclass of the abstract class, achieving polymorphism.

Example

// Define the abstract class Animal

abstract

class

Animal

{

   

// Abstract method: all animals make sounds

   

abstract

speak

(

)

:

void

;

}

// Define the Cat class inheriting from Animal

class

Cat

extends

Animal

{

   

// Implement the abstract method

    speak

(

)

:

void

{

        console.

log

(

"Meow meow meow!"

)

;

   

}

}

// Define the Dog class inheriting from Animal

class

Dog

extends

Animal

{

   

// Implement the abstract method

    speak

(

)

:

void

{

        console.

log

(

"Woof woof woof!"

)

;

   

}

}

// Define the function parameter type as the abstract class Animal

// This function can accept instances of any subclass of Animal

function

makeSpeak

(

animal

:

Animal

)

:

void

{

    animal.

speak

(

)

;

}

// Pass in different subclass instances to achieve different behaviors (polymorphism)

makeSpeak

(

new

Cat

(

)

)

;

makeSpeak

(

new

Dog

(

)

)

;

// Array of the abstract class type: can store instances of different subclasses

var

animals

:

Animal

[

]

=

[

new

Cat

(

)

,

new

Dog

(

)

]

;

Running result:

喵喵喵!

汪汪汪!

Polymorphism:When an abstract class is used as a type, what actually executes is the subclass's method implementation. This is the polymorphic feature of object-oriented programming.


The difference between abstract classes and interfaces

Both abstract classes and interfaces are used to define type specifications, but there are some key differences.

Understanding their differences helps in making the right choice in real development.

Feature abstract classes an interface
Instantiation Cannot be instantiated directly Cannot be instantiated directly
Method implementation Can have concrete implementations Can only have declarations (TypeScript 3.6+ allows default implementations)
Member modifiers Can add public, protected, private Can only have readonly
inheritance Single inheritance (can only extend one class) Multiple implementations (can implement multiple interfaces)
constructor Can have constructors Cannot have constructors

Selection advice:Use an abstract class when you need to share code; use an interface when you need to define a specification/contract; use an interface when you need multiple inheritance.


Complete example: payment system

Below is an example of a payment system implemented with abstract classes.

This example demonstrates the application of abstract classes in real projects.

Example

// Define the abstract payment class

abstract

class

Payment

{

   

// Abstract method: process payment, subclasses must implement

   

abstract

process

(

amount

:

number

)

:

boolean

;

   

// Concrete method: validate payment information

   

// All subclasses can use this method

    validate

(

)

:

void

{

        console.

log

(

"Validating payment information"

)

;

   

}

}

// Credit card payment class

class

CreditCardPayment

extends

Payment

{

   

// Credit card number

    cardNumber

:

string

;

   

// Constructor

    constructor

(

cardNumber

:

string

)

{

       

super

(

)

;

 

// Call the parent class constructor

       

this

.

cardNumber

=

cardNumber

;

   

}

   

// Implement the abstract method: process credit card payment

    process

(

amount

:

number

)

:

boolean

{

        console.

log

(

"Processing credit card payment: "

amount

)

;

       

return

true

;

   

}

}

// PayPal payment class

class

PayPalPayment

extends

Payment

{

   

// PayPal email

    email

:

string

;

   

// Constructor

    constructor

(

email

:

string

)

{

       

super

(

)

;

       

this

.

email

=

email

;

   

}

   

// Implement the abstract method: process PayPal payment

    process

(

amount

:

number

)

:

boolean

{

        console.

log

(

"Processing PayPal payment: "

amount

)

;

       

return

true

;

   

}

}

// Use polymorphism to handle different payment methods

var

payments

:

Payment

[

]

=

[

   

new

CreditCardPayment

(

"1234"

)

,

   

new

PayPalPayment

(

"test@example.com"

)

]

;

// Iterate over and process each payment method

for

(

var

_i

=

0

,

payments_1

=

payments

;

_i

<

payments_1.

length

;

_i

++

)

{

   

var

payment

=

payments_1

[

_i

]

;

   

// Call the inherited validation method

    payment.

validate

(

)

;

   

// Call the subclass's processing method

    payment.

process

(

100

)

;

}

Running result:

验证支付信息

处理信用卡支付: 100

验证支付信息

处理 PayPal 支付: 100

Application scenarios:Abstract classes are often used in framework design and business logic layering, for example in scenarios such as payment processing, user authentication, and data persistence.


Notes

Best practices:Use abstract classes when multiple classes need to share code and logic. Use interfaces when you only need to define specifications and contracts.


Summary

Abstract classes are an important part of TypeScript object-oriented programming.

Note:When designing class hierarchies, prefer abstract classes to share code and define specifications.