Java interfaces and abstract classes
|
|
Abstract class |
Interface |
|
Instantiation |
No |
No |
|
Class |
An inheritance relationship. A class can only use an inheritance relationship once. Multiple inheritance can be implemented by inheriting multiple interfaces. |
One class can implement multiple interfaces |
|
Data Member |
You can have your own |
Static objects cannot be modified, that is, they must be static final. |
|
Method |
Private and non-abstract methods are required |
Private Information is not allowed. The default value is public and abstract. |
|
Variable |
Private. The default value is friendly. The value can be redefined in the subclass or assigned again. |
Private is not allowed. The default value is the public static final type, and the initial value must be given. The implementation class cannot be redefined or its value cannot be changed. |
|
Design Concept |
Indicates the "is-a" relationship. |
Indicates the like-a relationship. |
|
Implementation |
To be inherited, use extends |
Use implements |
When to use the interface
A. the class and the class need to coordinate with specific interfaces, regardless of how they are implemented.
B. It can exist as an identifier that can implement specific functions, or it can be a pure identifier that does not exist in any interface method.
C. You need to regard a group of classes as a single class, and the caller only contacts this group of classes through interfaces.
D. a specific number of functions are required, and these functions may be completely unrelated.
When to use abstract classes
In a word, you can use a unified interface, instance variables, or default methods. The most common ones are:
A. defines A set of interfaces, but does not want to force each implementation class to implement all interfaces. Abstract class can be used to define a set of method bodies, or even empty method bodies, and then the subclass will select the methods that interest it to override.
B. In some cases, the pure interface alone cannot satisfy the coordination between classes. In addition, the variables in the class that indicate the State must be used to distinguish different relations. Abstract's mediation can well meet this requirement.
C. standardizes a set of methods for mutual coordination. Some of these methods are common and independent of the State. They can be shared without sub-classes; in other ways, each subclass needs to implement specific functions based on its own specific State.