Question of the Day: When to use an interface and when to use an abstract class?

The use of abstract classes is for code reuse, and the motivation for using interfaces is to achieve polymorphism.

Abstract classes are used for public use to improve reusability. (high availability)

Interfaces are for extensibility and maintainability. (down coupling)

for example:

Departing from Wuhan to Tiananmen Square in Beijing is a requirement.

Option 1: Ride a shared bicycle to the nearest subway entrance, then transfer to Line 2 or Line 4 to Wuhan High-speed Railway Station or Wuhan Tianhe Airport, and change to the high-speed rail or plane to Beijing. Like this, it can provide a complete set of itinerary planning, designed according to the two modes of the least time and cost and the least cost. This highly encapsulated solution is suitable for abstract classes.

Option 2: It is still the need to travel from Wuhan to Beijing.

You can hike, ride a shared bicycle, travel by car, call a taxi, etc. Such a relatively simple and low-coupling solution is suitable for using interfaces. Facilitate the maintainability of requirement changes.

Guess you like

Origin blog.csdn.net/qq_26695613/article/details/129348594