Differences between interfaces and abstract classes-I believe you will not confuse them after reading them.

Source: Internet
Author: User

 

I think the term "interface" must be familiar to all programmers using object-oriented programming languages, but I wonder if you have the following questions: What is the purpose of interfaces? What is the difference between it and abstract classes? Can I use abstract classes instead of interfaces? As a programmer, I often hear the phrase "interface-oriented programming". 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. They are not an independent programming idea more advanced than object-oriented programming, but affiliated with the object-oriented ideology, is a part of it. Or, it is one of the core ideas in the object-oriented programming system.

2. essence of interfaces

An interface is a collection of several methods without subject code. It has a unique name and can be implemented (or inherited) by a class or other interfaces ). It may look like the following in form:

Interface InterfaceName
{
Function onclick ()
{
This. style. display = 'none'; document. getElementById ('codehighlighter1 _ 24_121_Open_Text '). style. display = 'none'; document. getElementById ('codehighlighter1 _ 24_121_Closed_Image '). style. display = 'inline'; document. getElementById ('codehighlighter1 _ 24_121_Closed_Text '). style. display = 'inline ';
}
} "Src =" http://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif "alt =" "align =" top "> {
Void Method1 ();
Void Method2 (int para1 );
Void Method3 (string para2, string para3 );
}

 

So what is the essence of interfaces? Or what is the meaning of an interface. In my opinion, we can consider the following two perspectives:

1) An interface is a set of rules that specifies a group of rules that must be owned by the class or interface that implements this interface. It reflects the natural world, "if you are ...... You must be able ......" Concept.

For example, in nature, people can eat, that is, "If you are a person, you must be able to eat ". In computer programs, an IPerson (traditionally, the interface name starts with "I") interface should be generated, and a method named Eat () should be provided, every class that represents a person must implement the IPerson interface, which simulates the rule of "if you are a person, you must be able to eat" in nature.

From here, I want you to see some object-oriented ideas. One of the core of Object-oriented thinking is to simulate the real world and abstract things in the real world into classes. The whole program relies on instances of various classes to communicate and collaborate with each other to complete system functions, this is very consistent with the real world's operating conditions and is also the essence of Object-oriented thinking.

2) an interface is an abstract representation of similar things in a certain granularity view. Note that I have emphasized a certain granularity view, because the concept of "similar things" is relative, it varies with the granularity view.

For example, in my eyes, I am a person, which is essentially different from a pig. I can accept the saying that I am similar to my classmates, but I cannot accept that I am similar to a pig. However, in the eyes of an animal scientist, I and pig should be similar because we are both animals. He can think that both "human" and "pig" have implemented the IAnimal interface, while studying animal behavior, he will not treat me and pig separately, but will study the large granularity of "animal, but he will think that there is a fundamental difference between me and a tree.

Now I have changed to a genetic scientist, and the situation is different. Because biology can be inherited, in his eyes, I am not only different from pigs, it's no different from a mosquito, a bacterial, a tree, a mushroom, or even a SARS virus, because he thinks we all implement the IDescendable interface (Note: descend vi. genetics), that is, we are all genetic things. Instead of studying us separately, we will study all creatures as the same type. In his eyes, there is no human or virus, only genetic and non-genetic substances are available. But at least I am different from a rock.

Unfortunately, this happened. One day, there was a great man on the earth. His name was Lenin. He had a deep understanding of Marx and Engels's dialectical materialism, so he made a famous definition: material is the objective reality that can be reflected by consciousness. So far, there is no difference between me and a rock, a trace of air, an idiom, and an electromagnetic field that transmits mobile phone signals, because in Lenin's eyes, we are all objective realities that can be reflected by consciousness. If Lenin was a programmer, he would say that material is the instance generated by all classes that implement both the IReflectabe and IEsse interfaces. (Note: reflect v. reflect esse n. objectively and practically)

Maybe you will think that the above example is like a flaw, but this is exactly what the interface can mean. One of the object-oriented ideology and core is polymorphism. What is polymorphism? To put it bluntly, it is to deal with similar things in a specific granularity view without additional treatment. The reason why I dare to do this is that there is an interface. Like the genetic scientist, he understands that all creatures have implemented the IDescendable interface. As long as it is a creature, there must be the Descend () method, so he can study it in a unified manner, instead of studying each creature separately, it is exhausted.

It may not give you an intuitive impression on the nature and function of interfaces. In the following examples and Analysis of Several design patterns, you will experience the connotation of interfaces more intuitively.

3. Overview of interface-Oriented Programming

Through the above, I think you have an understanding of the concept of interfaces and interfaces. What is interface-oriented programming? My personal definition is:In System Analysis and architecture, layers and dependencies are distinguished. Each layer does not directly provide services to the upper layer (that is, it is not directly instantiated in the upper layer), but is defined by a set of interfaces, only the interface function is exposed to the upper layer. The upper layer only depends on the lower layer and does not depend on the specific class.

The benefits of doing so are obvious. First, they are of great benefit to system flexibility. When the lower layer needs to be changed, the upper layer does not need to be modified as long as the interface and interface functions remain unchanged. You can even replace the entire lower layer without modifying the upper layer code, just as we replace a WD 60 GB hard disk with a Seagate GB hard disk, and do not make any changes elsewhere in the computer, just remove the original hard disk and plug in the new hard disk, because the other part of the computer does not depend on the specific hard disk, but only relies on one IDE interface, as long as the hard disk implements this interface, it can be replaced. From this point of view, 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 interfaces is that developers of different components or layers can start work in parallel, just like creating a hard disk without waiting for a CPU or a monitor, as long as the interfaces are consistent, it is well-designed and can be developed in parallel to improve efficiency.

This article is here first. Finally, I would like to say that the essence of Object-oriented thinking is simulated reality, which is also the soul of my article. Therefore, it is very helpful to improve the system analysis and design capability to think about object-oriented things from reality.

In the next article, I will use an instance to demonstrate the basic methods of interface programming.

In the third article, I will analyze some interface-oriented programming ideas in the classic design model and analyze the interface-oriented ideas in the. NET layered architecture.

Supplement to this article:

I have read your replies carefully and are very happy to discuss technical issues with you. I would like to thank my friends who have affirmed me and those who have raised comments and questions. This prompted me to think more deeply and hope to make progress accordingly. Here I want to add something to discuss some concentrated questions in the replies.

1. About the "interface" in "interface-oriented programming" and the "interface" in specific object-oriented languages

A friend suggested that the word "interface" in "interface-oriented programming" should be wider than the interface in a pure programming language. I think it makes sense. What I wrote here is indeed not reasonable. I think the "interface" in object-oriented language refers to a specific code structure, for example, an interface defined by the interface keyword in C. The "interface" in "interface-oriented programming" can be said to be a structural component used to hide the specific underlying classes and implement polymorphism from the perspective of the software architecture.. In this sense, if an abstract class is defined to achieve polymorphism, it is reasonable to call this abstract class "interface. But is it unreasonable to use abstract classes to realize polymorphism? The second article is discussed below.

In summary, I think the two "interfaces" are different and interrelated.The interface in "interface-oriented programming" is an architectural component at the ideological level for realizing polymorphism and improving software flexibility and maintainability, the "interface" in a specific language is a means to implement the components in this idea into the code.

2. abstract classes and interfaces

This is a heated question. I am sorry that I did not discuss this issue weekly. My personal understanding of this issue is as follows:

From the perspective of specific code, these two concepts are easily vague, and even the interface is redundant, because from the perspective of specific functions, except for multiple inheritance (C #, java), abstract classes seem to completely replace interfaces. But does the interface exist to implement multi-inheritance? Of course not.In my opinion, the difference between an abstract class and an interface lies in the motivation for use. Abstract classes are used for code reuse, and interfaces are used for polymorphism.Therefore, if you are hesitant to use an interface or abstract class somewhere, you can think about your motivation.

My personal understanding is that the IPerson interface should not be defined. The key is how it is in a specific application. If Women and Man are in our project, they all inherit the Person, and most of the Methods of Women and Man are the same, there is only one method, DoSomethingInWC () is different (the example is vulgar, you may forgive me ), of course it is reasonable to define an AbstractPerson abstract class because it can include all other methods. The subclass only defines DoSomethingInWC (), which greatly reduces the amount of repeated code.

However, if the Women and Man classes in our program basically do not share the same code, and there is a PersonHandle class that needs to be instantiated, and they do not want to know that they are male and female, instead, it is necessary to define them as human beings and realize polymorphism.

All in all, the main difference between an interface and an abstract class lies in the motivation for use, not in itself. The definition of an item as an abstract class or interface depends on the context of the specific environment.

Furthermore, I think another difference between an interface and an abstract class is that the abstract class and its subclass should have a general and special relationship, and the interface is just a set of rules that its subclass should implement. (Of course, sometimes there may be general and special relationships, but the purpose of using interfaces is not here) for example, defining transportation as abstract classes, and defining cars, airplanes, and ships as subclasses, it is acceptable because cars, planes, and ships are a special means of transportation. For another example, the Icomparable interface only means that the class implementing this interface must be comparable. This is a rule. If the Car class implements Icomparable, we just say that there is a way in our Car to compare the two Car instances, which may be more expensive than the Car, it doesn't matter if the car is bigger than the other one, but we can't say that "a car is a special comparison." It doesn't work in grammar.

 

Transferred from: huihui-tropical fish

Source: http://www.cnblogs.com/huihui-gohay/archive/2009/12/13/1623070.html


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.