This article analyzes the difference between interfaces and abstract classes in Java learning, which is crucial for beginners to learn in depth and accurately grasp the concepts of Java programming. Details are as follows:
Java beginners often ask questions like: What is the difference between interfaces and abstract classes? On what basis do you choose to use interfaces and abstract classes?
The concepts of interfaces and abstract classes are different. The interface is the abstraction of actions, and the abstract class is the abstraction of the source.
The abstract class represents what this object is. The interface represents what this object can do. For example, men and women, these two classes (if they are classes...), their abstract class is people. Explain that they are all human beings.
People can eat, and dogs can also eat. You can define "eating" as an interface, and then let these classes implement it.
Therefore, in high-level languages, a class can only inherit one class (abstract class) (just as a person cannot be a living thing and a non-living thing at the same time), but it can implement multiple interfaces (eating interface, walking interface).
The first point. An interface is a variant of an abstract class, and all methods in the interface 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, but abstract classes cannot (Note: The original author made a mistake here. Abstract classes can be inherited. If all subclasses implement the methods in the abstract class, the subclass is not an abstract class; otherwise, one of them has not been implemented. Then the subclass is also an abstract class)
The third point. Interface definition methods cannot be implemented, while abstract classes can implement some methods.
The fourth point. The basic data type in the interface is static but the abstract image is not.
When you focus on the essence of a thing, use abstract classes; when you focus on an operation, use interfaces.
The functionality of abstract classes far exceeds that of interfaces, but the cost of defining abstract classes is high . Because in high-level languages (and in terms of actual design), each class can only inherit one class. In this class, you must inherit or write out all the common features of all its subclasses. Although the interface will be much weaker in function, it is only a description of an action. And you can implement multiple interfaces in one class at the same time. The difficulty will be reduced during the design stage.