This article describes the usage of Java interfaces and abstract classes. Share it for your reference, as follows:
interface
1 Because Java does not support multiple inheritance, with interfaces, a class can only inherit one parent class, but can implement multiple interfaces, and the interface itself can also inherit multiple interfaces.
2 The member variables in the interface are of the public static final type by default. Initialization that must be displayed.
3 The methods in the interface are of public abstract by default. Implicit declaration.
4 The interface has no constructor and cannot be instantiated.
5 An interface cannot implement another interface, but can inherit multiple interfaces.
6 If a class implements an interface, then all abstract methods in the interface must be implemented, otherwise the class must be defined as an abstract class.
Abstract Class
1 If a class is declared as abstract, this class cannot generate objects and can only be used inherited.
2 Abstract methods must exist in abstract classes.
3 There can be general variables and general methods in abstract classes.
4 Subclasses inherit an abstract class must implement its abstract methods unless the subclass is an abstract class.
private void print(){}; This statement represents the empty implementation of the method.
abstract void print(); This statement represents the abstraction of the method, without implementation.
The difference between interface and abstract class
1 The interface can only contain abstract methods, and abstract classes can contain ordinary methods.
2 The interface can only define static constant properties. Abstract classes can define both ordinary properties and static constant properties.
3 The interface does not contain constructor methods, and abstract classes can contain constructor methods.
Abstract class cannot be instantiated, but does not mean that it cannot have a constructor. Abstract class can have a constructor, and is a replacement class.
1 The interface is the core, which defines what to do and contains many methods, but does not define how these methods should be done.
2 If many classes implement an interface, then each of them needs to implement those methods in code.
3 If the implementations of some classes have something in common, an abstract class can be abstracted to allow the abstract class to implement the common code of the interface, while those personalized methods are implemented by each subclass.
Therefore, abstract classes are designed to simplify the implementation of interfaces. They not only provide the implementation of public methods, allowing you to develop quickly, but also allow your classes to implement all methods by themselves without tight coupling problems.
The application is very simple
1. Define interfaces first
2 If there are multiple interface implementations that have common parts, use abstract classes and integrate them.
The difference between interface and abstract class-I believe you won't be confused after reading it
I think that for programmers who use object-oriented programming languages, the term "interface" must be familiar, but I wonder if you have such doubts: What is the purpose of an interface? What is the difference between it and abstract classes? Can abstract classes be used instead of interfaces? Moreover, as programmers, you must often hear the phrase "interface-oriented programming", so what does it mean? What is the ideological connotation? What is the relationship with object-oriented programming? This article will answer these questions one by one.
1. What is the relationship between interface-oriented programming and object-oriented programming
First of all, interface-oriented programming and object-oriented programming are not horizontal. It is not an independent programming idea that is more advanced than object-oriented programming, but is attached to the object-oriented thinking system and belongs to its part. In other words, it is one of the essence of thought in object-oriented programming systems.
2. The nature of the interface
An interface is an ostensibly composed of several method definitions without body code. It has a unique name and can be implemented by a class or other interface (or can also be said to be inherited). It might look like the following in form:
interface InterfaceName { void Method1(); void Method2(int para1); void Method3(string para2,string para3); }So, what is the essence of an interface? Or what is the meaning of the existence of an interface? I think it can be considered from the following two perspectives:
1) An interface is a set of rules that specify a set of rules that a class or interface that implements this interface must have. It embodies the concept of nature that "if you are... you must be able..."
For example, in nature, people can eat, that is, "if you are human, you must be able to eat." Then when simulated in a computer program, there should be an IPerson (customically, the interface name starts with "I") interface, and there is a method called Eat(). Then we stipulate that every class representing "human" must implement the IPerson interface, which simulates the natural rule of "if you are a human, you must be able to eat".
From here, I think you can also see some object-oriented ideas. One of the cores of object-oriented thinking is to simulate the real world and abstract things in the real world into categories. The entire program relies on instances of various types to communicate with each other and cooperate with each other to complete the system functions. This is very consistent with the operating conditions of the real world and is also the essence of object-oriented thinking.
2) Interfaces are abstract representations of similar things on a certain granular view. Note that here I emphasize on a certain granular view, because the concept of "same thing" is relative, and it varies due to different granular views.
For example, in my eyes, I am a person, and there is a fundamental difference between me and a pig. I can accept the statement that my classmates and I are the same, but I must not accept that I am the same as a pig. However, if a zoologist's eyes are like pigs, I should be the same, because we are both animals, he can think that both "human" and "pig" have implemented the IAnimal interface. When he studies animal behavior, he will not treat me and pigs separately, but will study it from the larger particle size of "animal", but he will think that there is an essential difference between me and a tree.
Now that I have changed to a geneticist, the situation is different. Because all living things can be inherited, in his eyes, I am not only no different from pigs, but also from a mosquito, a bacteria, a tree, a mushroom, or even a SARS virus, because he would think that we have all implemented the IDescendable interface (note: descend vi. inheritance), that is, we are all heritable things. He will not study us separately, but will study all living things as similar types. In his eyes, there is no difference between humans and viruses, only heritable substances and non-heritable substances. But at least, there is still a difference between me and a stone.
But unfortunately, one day, a great man appeared on the earth, named Lenin. After he was familiar with MAX and Engels' masterpiece of dialectical materialism, he had a lot of experience, so he gave a famous definition: the so-called matter is an objective reality that can be reflected by consciousness. At this point, I am no longer different from a stone, a trace of air, an idiom, and the electromagnetic field that transmits mobile phone signals, because in Lenin's eyes, we are all objective reality that can be reflected by consciousness. If Lenin was a programmer, he would say this: the so-called matter is the instances generated by all classes that implement the two interfaces "IReflectabe" and "IEsse". (Note: reflect v. reflect esse n. objective reality)
Maybe you will think that my example above is nonsense, but this is exactly the meaning of the interface. One of the object-oriented ideas and core is polymorphism. What is polymorphism? To put it bluntly, it is to treat similar things indiscriminately at a certain granular view level and handle them uniformly. And the reason why I dare to do this is because there is an interface. Like that geneticist, he understood that all organisms have implemented the IDescendable interface. As long as they are organisms, there must be the Descend() method, so he can study them in a unified manner without studying each organism separately and eventually exhausting.
Maybe we can't give you an intuitive impression of the nature and function of the interface. Then in the following examples and the analysis of several design patterns, you will experience the connotation of the interface more intuitively.
3. Interface-oriented programming summary
Through the above article, I think you have an understanding of the ideological connotation of interfaces and interfaces. So what is interface-oriented programming? My personal definition is: in system analysis and architecture, we distinguish hierarchies and dependencies. Each level does not directly provide services to its upper layer (that is, not directly instantiated in the upper layer), but instead defines a set of interfaces, only exposing its interface functions to the upper layer. The upper layer only depends on the lower layer, and does not rely on specific classes.
The benefits of doing this are obvious, and first of all, it is very beneficial to system flexibility. When the lower layer needs to be changed, as long as the interface and interface functions remain unchanged, the upper layer does not need to make any modifications. You can even replace the lower layer without changing the upper layer code, just like we replace a WD 60G hard drive with a Seagate 160G hard drive. There is no need to make any changes in other parts of the computer, but just unplug the original hard drive and plug in the new hard drive, because the other parts of the computer do not rely on the specific hard drive, but only rely on an IDE interface. As long as the hard drive implements this interface, it can be replaced. From here, the interface in the program is very similar to the interface in reality, so I have always believed that the word interface is really similar!
Another advantage of using interfaces is that developers of different components or levels can start construction in parallel, just like those who build hard disks do not need to make CPUs or monitors. As long as the interfaces are consistent and the design is reasonable, development can be carried out in parallel, thereby improving efficiency.
This article will come here first. Finally, I would like to say something else: the essence of object-oriented is to simulate reality, which can also be said to be the soul of my article. Therefore, thinking more about object-oriented things from reality will be of great benefit to improving system analysis and design capabilities.
In the next article, I will use an example to show the basic methods of interface programming.
In the third article, I will analyze some interface-oriented programming ideas in the classic design pattern and analyze the interface-oriented ideas in the .NET hierarchical architecture.
Supplement to this article:
After carefully reading your replies, I am very happy to discuss technical issues with you. Thank you to your friends who gave affirmation, and also to your friends who put forward opinions and questions, which prompted me to think more deeply about something and hope to make progress through this. Here I would like to add something to discuss some of the more concentrated issues in the responses.
1. Regarding the two words "interface" in "interface oriented programming" and the specific object-oriented language "interface"
I saw a friend suggesting that the word "interface" in "interface oriented programming" should have a larger range than the interface in a simple programming language. After thinking about it, I thought it made sense. What I wrote here is indeed unreasonable. I think "interface" in object-oriented language refers to a specific code structure, such as an interface defined in C# with the interface keyword. The "interface" in "interface-oriented programming" can be said to be a structural component that refers to a more abstract level from the perspective of software architecture and from a more abstract level. In this sense, if an abstract class is defined and the purpose is to achieve polymorphism, then I think it is reasonable to call this abstract class also "interface". But is it reasonable to use abstract classes to implement polymorphism? Discuss in the second article below.
In summary, I think the concepts of two "interfaces" are both different and related to each other. Interfaces in "Interface-oriented programming" are architectural components at the ideological level for realizing polymorphism, improving software flexibility and maintainability, while "interfaces" in specific languages are the means to implement components in this idea into code.
2. About abstract classes and interfaces
I saw that this was a more intense issue in the reply. Sorry, I was not thinking well about this issue in the article. My personal understanding of this issue is as follows:
If we look at the specific code alone, these two concepts are easy to be blurred, and we even think that the interface is redundant, because from the specific function alone, except for multiple inheritance (C#, in Java), abstract classes seem to be able to replace interfaces completely. However, is the existence of interfaces to achieve multiple inheritance? Of course not. I think the difference between abstract classes and interfaces is the motivation to use. The use of abstract classes is for code reuse, while the motivation for using interfaces is for polymorphism. So, if you're hesitating about whether to use an interface or an abstract class somewhere, then you can think about what your motivation is.
Seeing a friend’s doubts about the IPerson interface, my personal understanding is that whether the IPerson interface should be defined depends on the specific application. If there are Women and Man in our project, both inherit Person, and most of the methods of Women and Man are the same, and there is only one method, DoSomethingInWC() is different (the example is vulgar, please forgive me), then of course, it is more reasonable to define an AbstractPerson abstract class, because it can include all other methods, and the subclass only defines DoSomethingInWC(), which greatly reduces the amount of duplicate code.
However, if the Women and Man classes in our program basically have no common code, and there is a PersonHandle class that needs to instantiate them, and do not want to know whether they are men or women, but just treat them as humans and implement polymorphism, then it is necessary to define them as interfaces.
In short, the difference between an interface and an abstract class is mainly due to the motivation for use, not itself. When a thing should be defined as an abstract class or an interface, it must be determined based on the context of the specific environment.
Furthermore, I think another difference between an interface and an abstract class is that there should be a general and special relationship between an abstract class and its subclass, while an interface is just a set of rules that its subclass should implement. (Of course, there may be a general and special relationship, but the purpose of our use of interfaces is not here.) For example, it is acceptable to define vehicles as abstract classes, and cars, aircraft, and ships as subclasses, because cars, aircraft, and ships are all special vehicles. For example, the Icomparable interface just says that the classes that implement this interface must be able to be compared, which is a rule. If the Car class implements Icomparable, it just means that there is a way in our Car to compare two Car instances, which may be more expensive than which car or larger than which car. It doesn't matter, but we can't say that "cars are special and can be compared", which is not grammatically applicable.
I hope this article will be helpful to everyone's Java programming.