[Turn] The difference between abstract class and interface and its application

Source: Internet
Author: User

The difference between abstract class and interface and its application

(This article is provided by Zhang Yang)

Abstract class and interface (Interface) are two important concepts in object-oriented programming. Since there are many similarities between the two in their own characteristics and application methods, such as cannot be instantiated, can be inherited (strictly speaking for the interface should be called implementation), so that in many people's minds abstract classes and interfaces are very vague, to when the use of abstract classes, when to use the interface is more confused.

The purpose of this paper is to help readers to understand the difference between abstract class and interface in the essence of thought and application, and if this can be done, the reader can choose and use abstract class and interface correctly according to the specific situation.

1. Abstract classes and interfaces are object-oriented concepts, not programming language-level concepts

If you want to understand the abstract class and interface correctly, the first thing to be clear is that these two concepts belong to the object-oriented thought level, and not belong to a programming language. For example, in C #, the language element declared with the interface keyword, which we call "interface", is actually inaccurate, and accurately, this should be called "the implementation mechanism of the interface in the C # language."

Object-oriented thought contains many concepts, and the concrete implementation mechanism of these concepts differs from object-oriented language. For example, there is no one keyword in C + + that corresponds to interface in C #, so there is no concept of interfaces in C + +? Not too! In C + +, if you want to define an interface, you can do this by defining all methods in a class as pure virtual methods [①] .

As you can see here, the same interface is defined in C # with the interface keyword, and C + + is defined by creating a class that contains only pure virtual methods, which is the same concept that has different implementation mechanisms in different specific languages. Similarly, there is no abstract keyword in C + + to define an abstraction class, but if a class contains at least one pure virtual method and its methods are not all pure virtual methods, then this class is called an abstract class.

As can be seen from the above analysis, if only to stay at the language level to understand the abstract class and interface, it is not accurate understanding of the true meaning of the two, because different languages on the same concept of the implementation of the Mechanism has a very big difference. If a C # beginner simply understood the two as "abstract class with the interface definition of the language element as the interface", then he would be confused when he approached C + +, because there was neither abstract nor interface in C + +. Instead, you can determine whether this is a class, an abstract class, or an interface through the case of a pure virtual method in a class.

Having identified the above problem, we can give a true definition of the abstract class and interface.

Abstract classes are classes that cannot be instantiated, but the methods in them can contain concrete implementation code.

An interface is a collection of method declarations that should contain only the declaration of a method and cannot have any implementation code.

The above definitions of abstract classes and interfaces are not related to any specific language, but are defined from the perspective of object-oriented thinking, and different languages can have different implementation mechanisms.

From the definition above, we can find a significant difference between the two at the ideological level: the abstract class is the class, the interface is the set, The two are essentially not a thing. This is the first difference we have summed up. Please be involved in the above bold words can be 10 times, the louder the better, but if the roommate or neighbor throwing eggs please do not look for me.

2. Abstract class is the abstraction of ontology, interface is the abstraction of behavior

Before starting this section, I would like to ask you a question, "I am a person" and "I can breathe" respectively to express the "I" and "people" and "I" and "breathing" relationship, then these two words expressed a relationship? If you can easily distinguish between the former means "is a" relationship, the latter means "can" relationship, then congratulations, you must also be able to easily distinguish between abstract classes and interfaces.

When reading this section, please be sure to remember the above question and the following sentence:

Abstract class representation " is a ( is-a ) " the abstraction of a relationship, an interface representation " Can ( Can-Do ) " the abstraction of a relationship.

Please read the above aloud words 10 times as usual.

OK, please wipe the eggs on your head, we continue.

As we can see from the bold words above, abstract classes and interfaces have a commonality-they are "abstractions of some kind", but different types. In fact, it is not surprising that the phrase "abstract" in the first sentence of the above sentence should be changed to "class", as we have said above, the abstract class is just a special class.

Let's explain is-a relationship first. In fact, the is-a relationship in English can be interpreted as two cases in Chinese, when is-a is used between an object and a class, meaning "This object is an instance of the class", for example, Guan Yu is an object, we can say "Guanyu is-a General", Which general is a class, which means that Guan Yu is an example of the general class. And when Is-a is used between two classes, I think the name is-a-kind-of is more accurate, that is, "is a kind" in Chinese, such as "General is-a person", which means that the class is a kind of human, Swapping object-oriented terminology can be described as follows: General is a subclass of person (sub type), the person is the parent or superclass (super type) of general, and general inherits from person.

This latter kind of is-a relation is the relation that the abstract class expresses. It can be seen from the analysis that the relationship between the abstract class is actually one of the three main characteristics of object-oriented-inheritance (inheritance), that is, the relationship between the abstract class and the general class and the inheritance between the class is no different, and abstract class compared to ordinary class, in addition to non-instance, there is no difference. Abstract classes occur because, at a higher level of abstraction, some methods (often pure virtual methods) cannot be implemented and must be implemented by their subclasses in their own different circumstances. Because it contains pure virtual methods, it does not make sense to instantiate this kind of class, but we want to abstract out some of these subclasses to reduce the duplication of code, so there is an abstract class-it contains reusable parts, but does not allow instantiation.

Therefore, the motivation of an abstract class is to reuse code under restrictions that do not allow instantiation. Please keep this motive in mind.

Then talk about interfaces and can-do relationships.

We know that the basic idea of object-oriented programming is to accomplish the function of the program through mutual cooperation between objects. Specifically, in object-oriented programming, each class is required to hide internal details (this is called encapsulation), exposing only a common set of methods, and the objects are programmed to function by invoking each other's public methods.

As you can see, in object-oriented thinking, objects and objects do not need to be understood at all, and callers can even have no idea who the callee is, as long as they know what the callee "can do". This is like dialing 110 alarm, you do not know what the other person looks like, what clothes to wear, knot not married, there are no children, you do not know where the other side, the object is who, but you know each other must be "able to take the police", so you can successfully complete the alarm.

This "can do" is can-do relationship, when we abstract this can-do relationship, forming a can-do relationship, this is the interface. So what are the motivations for using interfaces? one of the motivations is loose coupling. we know that "low coupling" is an important principle in object-oriented programming, and a large part of coupling is called relationship, and the term object-oriented is called "dependency". If there is no interface, the caller will have to rely on the callee, as in no 110 alarm era, you only know a pick up police, do not know the other police call, then when you call the police, you have to call the police, if one day this pick-up police leave or sick, you can not call the police, Unless you get to know one of the pick-up officers. At this point, we say that you rely heavily on this pick-up, also called tight coupling. But after 110 alarm is not the same, we will be "can answer the police" as an interface, the interface has a method of "call the police", and Dial 110, the person who is the head of the phone must be the realization of this interface, the alarm is no longer dependent on the specific police, but rely on the "can connect the police" interface, which is

Therefore, the interface can also be regarded as a set of rules, it is the guarantor of the caller, the constraints on the callee. in the above example, the alarm can be connected to the caller (caller) to ensure that the calling object can be connected to the police, while the constraints of the police Department must have a realization of the interface of the person arranged in front of the call. It doesn't matter if it's a robot or a janitor who has just been trained for two hours.

another motive for using interfaces is to achieve polymorphism [②] .

Imagine you are assigned to a brand new research and development team as the supervisor, the first day of work in the morning, a group of people stand in front of you waiting for you to talk, you do not know them, do not understand their respective positions, but you can say "all go to work", so everyone disarray, programmers to write procedures, accounting to check the accounts, Salesman out to contact customers ... When you do this, you use the interface to achieve polymorphism. Because you know, they all implement the "can work" interface, although each person to the "work" specific implementation is not the same, but it does not matter, you just call their "work" method, they do their own things. If you can not interface to the use of polymorphism, you will have to say: "Programmers to write programs, accounting to the audit, the salesman quickly go out to contact customers ...", this is really very laborious.

Make a summary of the content of this section:

Abstract class representation " is a ( is-a ) " the abstraction of a relationship, which abstracts the ontology of a class, uses the motive to reuse code without allowing instantiation. An interface represents an abstraction of a " can (can-do)" relationship, which abstracts the behavior of a class, Its use motivation is the coupling between loose objects and the implementation of program polymorphism.

OK, as usual, read 10 times, but this time I allow you to meditate, because I am afraid this is not an egg but a brick.

After the analysis above, I think you can easily choose between the abstract class and the interface. If you are extracting the public code of a series of classes and reducing the duplication of code, and these classes and abstract classes can be expressed as is-a relationships, use abstract classes; If you are to abstract a group or a set of behaviors to loose the coupling between objects or to achieve polymorphism, then use interfaces.

3. Discussion of abstract classes and interfaces in C #

In this section we discuss one of the best known differences in the C # language: in C # , a class can inherit at most one abstract class, but multiple interfaces are implemented.

If you can fully understand that the abstract class corresponds to the is-a and the interface corresponds to the can-do, then this constraint will not be surprised. Because logically, a class can only "be one" in all classes of the same level of abstraction, but "capable of many things." The same level of abstraction here refers to a complete collection of inheritance relationships that do not exist with each other.

For example, {pig, cows, dogs, cats} can be seen as having the same level of abstraction, one of its lower classes can only be one of the subclasses, a class may not be both the sub-class of cattle and the sub-class of pigs, but it is possible to be both a sub-class of cattle and animal subclasses, such as cows, this is because "animal" and "cow itself is a subclass of "animal".

in general, if ClassA is a ClassB sub-class, but also ClassC subclass, then there must be ClassB is a ClassC the subclass or ClassC is a ClassB sub-class.

In other words, it is logically not logical for a class to inherit at the same time two classes that do not have an inheritance relationship with each other. This explains why C # is not allowed to inherit more than one abstract class at a time. If a class inherits two abstract classes, logically, there must be an inheritance relationship between the two abstract classes, so just let the class inherit the more specific abstract class. For example, the original design for "cows" at the same time inherit "cattle" and "animals", but it is easy to find that "cattle" and "animals" already exist inheritance relations, "cattle" is inherited from the "animal", so the inheritance relationship can be modified to "cows" only Inherit "cattle", and let "cattle" inherited from "animals", so that the elimination of multiple inheritance.

The can-do relationship between interfaces does not logically have such contradictions, so C # allows the implementation of multiple interfaces, specifically why the reader to consider their own.

Incidentally, C + + allows multiple inheritance is because C + + non-abstract classes, abstract classes and interfaces are implemented using classes, but not in the language level area into different language elements, in fact, if the design is good, but also should not appear on the multiple inheritance of the abstract class, C # on the language level of the constraints, more conducive to good design , and C + + is more flexible in this area and needs to be grasped by the developers themselves, so C + + is more difficult for beginners to grasp abstract classes and methods.

[Turn] The difference between abstract class and interface and its application

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.