Summary of java interface and abstract class usage examples
This article describes the usage of Java interfaces and abstract classes. Share with you for your reference, as follows:
Interface
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 inherit multiple interfaces.
2. The member variables in the interface are of public static final type by default. Initialization that must be displayed.
3. All methods in the interface are public abstract by default. Implicit declaration.
4. The interface has no constructor and cannot be instantiated.
5 interface cannot implement another interface, but can inherit multiple interfaces.
If a class implements an interface, it must implement all abstract methods in the interface, otherwise the class must be defined as an abstract class.
abstract class
If a class is declared abstract, it cannot generate objects and can only be inherited.
2 abstract methods must exist in abstract classes.
3 abstract classes can have general variables and general methods.
Subclasses inherit abstract classes and must implement the abstract methods in them, unless the subclass is an abstract class. private void print(){}; This statement represents an empty implementation of a method. abstract void print(); This statement represents the abstraction of the method without implementation.
Differences between interfaces and abstract classes
1 interfaces can only contain abstract methods, and abstract classes can contain ordinary methods. 2. The interface can only define static constant attributes. Abstract classes can define either common attributes or static constant attributes. 3. The interface does not contain construction methods, and the abstract class can contain construction methods.
The fact that an abstract class cannot be instantiated does not mean that it cannot have a constructor. An abstract class can have a constructor for extension by an inherited class
1 interface is the core. It defines what to do and contains many methods, but it does not define how these methods should do. 2 if many classes implement an interface, each of them should implement those methods with code. 3 if the implementation of some classes has something in common, an abstract class can be abstracted to enable the abstract class to implement the public code of the interface, while those personalized methods are implemented by various subclasses.
Therefore, the abstract class is to simplify the implementation of the interface. It not only provides the implementation of public methods so that you can develop quickly, but also allows your class to implement all methods by itself without tight coupling.
The application situation is very simple. 1. Give priority to defining interfaces. 2. If multiple interface implementations have common parts, use abstract classes, and then integrate them.
The difference between interface and abstract class -- I'm sure you won't be confused after reading it
I think the term "interface" must be familiar to programmers who use object-oriented programming language, but do you have such doubts: what is the purpose of the interface? What is the difference between it and abstract classes? Can we use abstract classes instead of interfaces? Moreover, as a programmer, 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 at the same level. It is not an independent programming idea more advanced than object-oriented programming, but attached to the object-oriented ideological system and belongs to its part. In other words, it is one of the quintessence of object-oriented programming system.
2. Essence of interface
On the surface, an interface is a collection of several method definitions without body code. It has a unique name and can be implemented (or inherited) by classes or other interfaces. Its form may be as follows:
So what is the essence of the interface? Or what is the meaning of the interface. I think it can be considered from the following two perspectives:
1) An interface is a set of rules, which specifies a set of rules that must be owned by the class or interface that implements the interface. It embodies the concept of nature that "if you are..., you must be able to...".
For example, in nature, people can eat, that is, "if you are a person, you must be able to eat". Then when simulating into a computer program, there should be an iperson (traditionally, the interface name starts with "I") interface and a method called eat (). Then we stipulate that every class representing "human" must implement the iperson interface, which simulates the rule of nature that "if you are a human, you must be able to eat".
From here, I think you can also see something about object-oriented thinking. One of the core of object-oriented thought is to simulate the real world and abstract things in the real world into classes. The whole program relies on the instances of various classes to communicate and cooperate with each other to complete the system functions, which is very in line with the operation status of the real world and the essence of object-oriented thought.
2) An interface is an abstract representation of similar things in a certain granularity view. Note that I emphasize here that in a certain granularity view, because the concept of "similar things" is relative, it is different because of different granularity views.
For example, in my eyes, I am a person, which is essentially different from a pig. I can accept that my classmates and I are the same kind, but I can never accept that I and a pig are the same kind. However, in the eyes of a zoologist, pigs and I should be the same kind, because we are both animals. He can think that "people" and "pigs" have realized the ianimal interface, and when he studies animal behavior, he will not treat me and pigs separately, but will study from the larger granularity of "animals", but he will think that I am essentially different from a tree.
Now, a geneticist has changed. The situation is different. Because the organism can inherit, so in his eyes, I am not only different from the pig, but what is different from a mosquito, a bacterium, a tree, a mushroom and even a SARS virus. Because he will think that we have all realized the interface of idescendable (Note: descent VI. heredity), that is, we are heritable things. He will not study us separately, but will study all organisms as the same kind. In his eyes, there is no difference between human and virus, only heritable materials and non heritable materials. At least, I am different from a stone.
Unfortunately, something happened. One day, a great man named Lenin appeared on the earth. After reading Max and Engels' great works of dialectical materialism, he had some experience, so he made a famous definition: the so-called material is the objective reality that can be reflected by consciousness. So far, I am no different from a stone, a trace of air, an idiom and the electromagnetic field transmitting mobile phone signals, because in Lenin's eyes, we are objective reality that can be reflected by consciousness. If Lenin were a programmer, he would say this: the so-called material is the instance generated by all classes that implement both "ireflectable" and "iesse" interfaces at the same time. (Note: reflect v. reflect esse n. objective reality)
You may think my above example is nonsense, but this is the meaning of the existence of the interface. One of the object-oriented ideas and core is called polymorphism. What is polymorphism? To put it bluntly, it means that similar things are treated in a unified manner without distinction at a granularity view level. The reason why I dare to do this is because there are interfaces. Like that geneticist, he knows that all creatures have implemented the idescendable interface. As long as it is a creature, there must be the method of descent (), so he can study it uniformly, instead of studying each creature separately and finally dying of fatigue.
It may not 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. Overview of interface oriented programming
Through the above, I think you have an understanding of the interface and the ideological connotation of the interface, so what is interface oriented programming? My personal definition is: in system analysis and architecture, we should distinguish between layers and dependencies. Each layer does not directly provide services to its upper layer (that is, it is not directly instantiated in the upper layer), but only exposes its interface functions to the upper layer by defining a group of interfaces. The upper layer only depends on the interface to the lower layer, not on specific classes.
The benefits of this are obvious. First, it is very good for system flexibility. When the lower layer needs to be changed, as long as the interface and interface function remain unchanged, the upper layer does not need to make any modification. You can even replace the entire lower layer without changing the upper layer code. For example, we replace a 60g WD hard disk with a 160g Seagate hard disk. There is no need to make any changes in other parts of the computer, but just unplug the original hard disk and plug in the new hard disk, because other parts of the computer do not rely on a specific hard disk, but only on an IDE interface, As long as the hard disk implements this interface, it can be replaced. From here, the interface in the program is very similar to the interface in reality, so I always think that the word interface is really similar!
Another advantage of using the interface is that developers at different parts or levels can work in parallel, just like those who build hard disks do not have to wait for CPU or display. As long as the interface is consistent and the design is reasonable, they can develop in parallel, so as to improve efficiency.
This article ends here first. Finally, I want to improve the quality of Chang Yun's wood and wood, and ensure that the quality of Chang Yun's wood and wood can be improved, the art can be improved, and the quality of Chang Yun's wood and wood can be improved Υ Please note
In the next article, I will use an example to show the basic methods of interface programming.
In the third part, I will analyze some interface oriented programming ideas in classical design patterns Net layered architecture.
Supplement to this article:
After reading your replies carefully, I am very glad to discuss technical issues with you. Thank you for your positive comments, and also thank you for your comments and questions, which prompted me to think more deeply about some things and hope to make progress. Here I would like to add something to discuss some of the more focused issues in the reply.
1. About "interface" in "interface oriented programming" and "interface" in specific object-oriented language
I saw a friend put forward that the word "interface" in "interface oriented programming" should have a wider range than the interface in a simple programming language. After thinking, I think it makes sense. What I write here is really unreasonable. I think "interface" in object-oriented language refers to a specific code structure, such as the interface defined with the interface keyword in c#. The "interface" in "interface oriented programming" can be said to be a structural component used to hide specific underlying classes and realize polymorphism 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, I think it is reasonable to call this abstract class "interface". But is it reasonable to implement polymorphism with abstract classes? Discussed in Article 2 below.
To sum up, I think the two concepts of "interface" are different from and related to each other. The interface in "interface oriented programming" is an ideological component used to realize polymorphism and improve software flexibility and maintainability, and the "interface" in specific language is a means to implement the component in this idea into code.
2. About abstract classes and interfaces
See the reply, this is a hotly discussed issue. I'm sorry I wasn't thoughtful enough to discuss this issue in my article. My personal understanding of this issue is as follows:
From the perspective of specific code, it is easy to blur these two concepts, and even think that the interface is redundant, because from the perspective of specific functions, Except multiple inheritance (c#, in Java), abstraction can completely replace interfaces. However, is the existence of interfaces to realize multiple inheritance? Of course not. I think the difference between abstract classes and interfaces lies in the use motivation. Abstract classes are used for code reuse, while interfaces are used for polymorphism. Therefore, if you are using interfaces for a certain place, should you use interfaces or extract them When you are hesitant, think about your motivation.
Seeing that some friends have questioned 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, they both inherit person, and most of the methods of women and man are the same, Only one method dosomethingwc () is different (the example is vulgar, please forgive me). Of course, it is reasonable to define an abstractperson abstract class, because it can include all other methods, and the subclass only defines dosomethingwc (), which greatly reduces the amount of repeated 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 people and implement polymorphism, it is necessary to define interfaces.
In short, the difference between an interface and an abstract class lies mainly in the motivation for use, not in itself. Whether a thing should be defined as an abstract class or an interface depends on the context of the specific environment.
Moreover, I think another difference between an interface and an abstract class is that an abstract class and its subclasses should have a general and special relationship, while an interface is only a set of rules that its subclasses should implement. (of course, sometimes there may be general and special relationships, but the purpose of using the interface is not here). For example, it is acceptable to define the vehicle as an abstract class and the automobile, aircraft and ship as subclasses, because the automobile, aircraft and ship are all special vehicles. Another example is the IComparable interface, which only means that the class implementing the interface must To be able to compare, this is a rule. If the car class implements IComparable, it just means that there is a method in our car that can compare the instances of two cars, which may be more expensive or larger than which car. It doesn't matter, but we can't say that "cars are special and can be compared", which doesn't matter in grammar.
I hope this article will be helpful to you in Java programming.