In depth analysis of the difference between Java interface and abstract class

This paper analyzes the difference between interface and abstract class in java learning, which is very important for beginners to deeply learn and accurately master the concept of Java programming. Details are as follows:

Java beginners are often easy to ask such questions: what is the difference between interfaces and abstract classes? What is the basis on which you choose to use interfaces and abstract classes?

The concepts of interface and abstract class are different. Interfaces are abstractions of actions, and abstract classes are abstractions of roots. The abstract class represents what this object is. Interface represents what this object can do. For example, men and women, these two classes (if they are classes...), their abstract class is human. It shows that they are both human.

People can eat and dogs can eat. You can define "eating" as an interface and let these classes implement it Therefore, in high-level languages, a class can only inherit one class (abstract class) (just as people can't be both biological and non biological), but can implement multiple interfaces (eating interface and walking interface).

First, 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.

Second, interfaces can be inherited, but abstract classes can't (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; on the contrary, if one is not implemented, the subclass is also an abstract class)

Third, interface definition methods cannot be implemented, while abstract classes can implement some methods.

Fourth, the basic data type in the interface is static, but the class image is not.

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

Abstract classes are much more powerful than interfaces, but defining abstract classes is expensive. Because for high-level languages (in terms of actual design), each class can only inherit one class. In this class, you must inherit or write all the commonalities of all its subclasses. Although the interface will weaken a lot in function, it is only a description of an action. Moreover, you can implement multiple interfaces in a class at the same time. It will reduce the difficulty in the design stage.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>