乐闻世界logo
搜索文章和话题

Differentiate between extends and implements in TypeScript?

1个答案

1

In TypeScript, extends and implements are two common keywords used to describe relationships between classes and interfaces, with distinct functionalities and purposes.

Extending (Extends)

Functionality: Extending is a fundamental concept in object-oriented programming, primarily used for class inheritance. By using the extends keyword, a class can inherit properties and methods from another class. This allows subclasses to have their own unique members while reusing the functionality of the parent class.

Example:

typescript
class Animal { breathe() { console.log("Breathing..."); } } class Dog extends Animal { bark() { console.log("Woof! Woof!"); } } const myDog = new Dog(); myDog.breathe(); // Inherited from Animal class myDog.bark(); // Dog class's own method

In this example, the Dog class extends the Animal class, meaning instances of Dog can use the breathe method defined in the Animal class.

Implementing (Implements)

Functionality:

The implements keyword is used for the relationship between classes and interfaces. When a class implements an interface, it must implement all methods and properties declared in the interface. Interfaces define only the structure of members without specific implementation; the concrete implementation must be completed within the class that implements the interface.

Example:

typescript
interface IAnimal { breathe(): void; sleep(): void; } class Cat implements IAnimal { breathe() { console.log("Cat breathing..."); } sleep() { console.log("Cat sleeping..."); } } const myCat = new Cat(); myCat.breathe(); myCat.sleep();

In this example, the Cat class implements the IAnimal interface, so it must specifically implement the breathe and sleep methods.

Summary

  • Extending is used for inheritance relationships between classes, where subclasses inherit properties and methods from the parent class.
  • Implementing is used for contractual relationships between classes and interfaces, where the class must implement all properties and methods declared in the interface.

Both are essential object-oriented features in TypeScript that help developers write structured, maintainable code.

2024年8月3日 16:33 回复

你的答案