Differences between abstract classes and interfaces in C,

Source: Internet
Author: User

Differences between abstract classes and interfaces in C,

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
{
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

So 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.

 

Supplement to this article:

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

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 is thatMotivation.Abstract classes are used for code reuse, and interfaces are used for polymorphism..So,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.

 

What is the difference between abstract classes and interfaces in C #. NET?

The concepts of interfaces and abstract classes are different.The interface is the abstraction of actions, and the abstract class is the abstraction of the source.

The abstract class indicates what this object is. The interface indicates what this object can do.. For example, men and women (if they are classes ......), Their abstract class is human. It means they are all people.

People can eat, dogs can also eat, you can define "eat" as an interface, and then let these classes implement it.

Therefore, in advanced languages, a class can only inherit one class (abstract class) (just as humans cannot be both biological and non-biological ), however, multiple interfaces (meal and walking interfaces) can be implemented ).

 

Next, let's talk about the twoApplicationDifferences:
Interfaces are mainly used to define communication contracts between modules in the system architecture design method.
Abstract classes play a role in code implementation and can be reused.

The template method design pattern is a typical application of abstract classes.

 

Best Answer:
1 abstract class
(1) abstract methods are declared only, but do not contain implementations. They can be considered as virtual methods without implementations.
(2) abstract classes cannot be instantiated.
(3) abstract classes can but do not have to have abstract attributes and abstract methods. However, once an abstract method is available, you must declare this class as an abstract class.
(4) The specific derived class must overwrite the abstract method of the base class.
(5) An abstract derived class can overwrite or overwrite the abstract methods of the base class. If not overwritten, the specific derived class must overwrite them. For example:

Using System;
Public abstract class A // abstract class
{
Private int num = 0;
Public int Num // abstract class containing attributes
{
Get
{
Return num;
}
Set
{
Num = value;
}
}

Public virtual int getNum () // abstract class contains virtual Methods
{
Return num;
}

Public void setNum (int n) // The abstract class contains common methods.
{
This. num = n;
}

Public abstract void E (); // abstract method E in Class
}

Public abstract class B: A // because class B inherits the abstract method E in class A, class B also becomes an abstract class
{

}
Public class C: B
{
Public override void E () // override the abstract method inherited from Class. If Class B also defines an abstract method, it must be rewritten.
{
// Throw new Exception ("The method or operation is not implemented .");
}
}

Public class Test
{
Static void Main ()
{
C c = new C ();
C. E ();
}
}


2. Access Port
(1) The interface cannot be instantiated.
(2) interfaces can only contain method declarations.
(3) interface members include methods, attributes, indexers, and events.
(4) The interface cannot contain constants, fields (fields), constructors, destructor, and static members. For example:
Public delegate void EventHandler (object sender, Event e );
Public interface ITest
{
// Int x = 0;
Int
{
Get;
Set;
}
Void Test ();
Event EventHandler Event;
Int this [int index]
{
Get;
Set;
}
}
(5) All the members in the interface are public by default, so the interface cannot have a private Modifier
(6) The derived class must implement all the members of the interface.
(7) A class can directly implement multiple interfaces separated by commas.
(8) An interface can have multiple parent interfaces. The class implementing this interface must implement all the members of all parent interfaces.

Iii. abstract classes and interfaces
Similarities:
(1) can be inherited
(2) cannot be instantiated.
(3) All methods can contain method declarations.
(4) The derived class must implement the unimplemented method.
Partition:
(1) abstract base classes can define fields, attributes, and methods. The interface can only define attributes, indexers, events, and method declarations, and cannot contain fields.
(2) abstract classes are incomplete classes and need to be further refined. interfaces are a behavior specification. Microsoft's custom interface always carries the able field to prove that it is a class of expression "I can do it ..."
(3) The interface can be implemented in multiple ways, and the abstract class can only be inherited by a single
(4) abstract classes are more defined in a series of closely related classes, while interfaces are mostly classes with loose relationships but all implement certain functions.
(5) abstract classes are abstract concepts from a series of related objects, so they reflect the internal commonalities of things. interfaces are a functional Convention defined to satisfy external calls, therefore, it reflects the external characteristics of things.
(6) The interface basically does not have any specific characteristics of inheritance. It only promises the methods that can be called.
(7) interfaces can be used to support callback, but inheritance does not have this feature
(8) The specific methods implemented by abstract classes are virtual by default, but the interface methods in the class implementing interfaces are non-virtual by default. Of course, you can also declare them as virtual
(9) If an abstract class implements an interface, you can map the methods in the interface to the abstract class, instead of implementing the methods in the abstract class.

Related Article

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.