An in depth look at the differences between Java interfaces and abstract classes

  • 2020-04-01 03:26:02
  • OfStack

This article explores the difference between interfaces and abstract classes in Java learning, which is crucial for beginners to learn more about and accurately grasp the concepts of Java programming. Details are as follows:

It's easy for Java beginners to ask: what's the difference between an interface and an abstract class? What are your reasons for choosing to use interfaces and abstract classes?

Interfaces are not the same as abstract classes. An interface is an abstraction of an action, and an abstract class is an abstraction of a root.
The abstract class represents what the object is. The interface represents what the object can do. For example, men, women, these two categories (if they are categories...) Their abstract class is people. That means they're human.

People can eat, dogs can eat, you can define "eat" as an interface, and then let these classes implement it.
So, in a high-level language, a class can only inherit from one class (abstract class) (just as a person cannot be both living and non-living), but can implement multiple interfaces (eating and walking).

The first point. An interface is a variant of an abstract class, in which all methods are abstract. An abstract class is a class that declares the existence of a method without implementing it.

The second point. Interfaces can be inherited, not abstract classes. If one is not implemented, the subclass is an abstract class.)

The third point. Interfaces define methods that cannot be implemented, while abstract classes can implement partial methods.

The first four. The basic data type in the interface is static and the abstract is not.

When you focus on the essence of something, use abstract classes; When you focus on an operation, use an interface.

Abstract classes do more than interfaces, but they are expensive to define . Because high-level languages (and by design) can inherit only one class per class. In this class, you must inherit or write all the commonalities of all its subclasses. Although the interface is much weaker functionally, it is only a description of an action. And you can implement multiple interfaces in a class at the same time. It will be easier in the design phase.


Related articles: