Post basic knowledge-differences between abstract classes and interfaces in. net

Source: Internet
Author: User

I. abstract classes

(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:

Select crm oa erp scm invoicing and other software! Http://www.xingzhu.net.cn

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 = 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:

Select crm oa erp scm invoicing and other software! Http://www.xingzhu.net.cn

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.

Rules:
1. abstract classes are mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.
2. If you want to design a large functional unit, use an abstract class. If you want to design a small and concise functional block, use an interface.
3. If you want to create multiple versions of a component, create an abstract class. The interface cannot be changed once it is created. If you need a new version of the interface, you must create a new interface.
4. If you create a function that will be used across a wide range of different objects, use the interface. If you want to provide general implemented functions among all the implementations of the component, use the abstract class.
5. Analyze objects and extract internal commonalities to form abstract classes to express the object nature, that is, "What ". Interfaces are preferred when external calls or functions need to be expanded
6. A good interface definition should be specific and functional, rather than multi-functional, otherwise it may cause interface pollution. If a class only implements a function of this interface and has to implement other methods in the interface, it is called interface pollution.
7. Avoid using inheritance to implement the build function, but use black box multiplexing, that is, object combination. As the hierarchy of inheritance increases, the most direct consequence is that when you call a class in this group, you must load all of them into the stack! The consequences can be imagined. (Based on the stack principle ). At the same time, some interested friends can note that Microsoft often uses the object combination method when building a class. For example, in Asp.net, the page class has server request and other attributes, but in fact they are all objects of a certain class. This object of the page class is used to call the methods and attributes of other classes. This is a very basic design principle.
For example:
Window forms can be designed with abstract classes. Public operations and attributes can be put into an abstract class, so that the forms and dialogs can inherit from this abstract class and then be expanded and improved according to their own needs.
The print operation can be provided as an interface to each form that requires this function. because the content of the form is different, you must implement your own printing function according to their own requirements. You can call this function only through the interface, instead of printing the form.

4. Other articles
Commonalities, personalities, and choices
In some books, C # recommends using interfaces to replace abstract classes, and emphasizes many advantages of using interfaces, there are still many differences between the two, and the existence of such differences inevitably determines the differences in applicable scenarios. For example, in the abstract base class, some methods can provide default implementations, this avoids repeated implementation of them in subclass to improve code reusability, which is the advantage of abstract classes. interfaces can only contain abstract methods. The key to when to use abstract base classes and when to use interfaces depends on how the user views the relationships between inherited classes. the user is more concerned with the differences in personality between them or the common connections between them. Here is an example of life.
If three objects are people, fish, and frogs, you can design a base class for them to summarize the relationships between them, first, you must feel that the differences between individuals are large, and it is difficult to abstract the commonalities. However, if you want to summarize the commonalities between their behaviors, you may think about it and realize that they can all swim, but they have different ways of swimming. In this case, you should consider using interfaces instead of abstract base classes for three reasons:
1. personality is greater than commonality.
2. There are some identical behaviors between different personalities.
3. The implementation methods of the same behavior are quite different.
At this time, we will give you three objects, namely, carp, carp, and goldfish, which still allow you to design a base class to summarize the relationships between them, the first thing you realize is that they all belong to fish, and the second is that their swimming methods may be slightly different. In this case, you should use abstract base classes instead of interfaces, there are also three reasons:

 

Select crm oa erp scm invoicing and other software! Http://www.xingzhu.net.cn

Interface iswim
{
Void swim ();
}

Public class person: iswim
{
Public void swim ()
{
// Specify Ming in person's style.
}
}

Public class frog: iswim
{
Public void swim ()
{
// Specify Ming in frog's style.
}
}

Public class fish: iswim
{
Public void swim ()
{
// Specify Ming in fish's style.
}
}

1. commonality is greater than individuality
2. individuals with the same commonalities must have the same attributes and behaviors.
3. Implementation of the same behavior is different.

Abstract Public class fish
{
Abstract Public void swim ();
}

Public class carp: Fish
{
Public override void swim ()
{
// Swim like a Crucian Carp
}
}

Public class carp: Fish
{
Public override void swim ()
{
// Swim like a carp
}
}

Public class goldfish: Fish
{
Public override void swim ()
{
// Swim like a goldfish
}
}

 

Observe that the third reason for using interfaces or abstract base classes is the same. It describes the concept of polymorphism in object-oriented systems, that is, the method of overwriting the parent class is implemented. At runtime, the corresponding method is called Based on the passed object reference. The second reason is that there are differences. The interface emphasizes that the inherited objects have the same behavior, while the abstract class also emphasizes that the inherited objects have the same attributes. The reason for truly separating interfaces from abstract base classes is
I. summarized as follows:

Use interfaces when looking for functional commonalities between objects with large differences.
Abstract base classes are used when looking for functional differences between objects with many commonalities.
Through comparison between the same and different types, we can only talk about interfaces and abstract classes, each of which has its own strengths, but has no advantages. In actual programming practices, we need to take appropriate measures based on actual situations. However, the following experiences and accumulation may give you some inspiration, except for some of my accumulation, many of them come from classic networks. I believe they can withstand the test. So in terms of rules and occasions, the most important thing for us to learn these classics is to apply what we have learned. Of course, I will give my family a wide smile.

Rules and occasions
1. Remember, one of the most important principles of Object-oriented thinking is interface-oriented programming.
2. With the help of interfaces and abstract classes, many ideas in 23 design patterns are cleverly implemented. I think the essence is simply abstract programming.
3. abstract classes should be mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.
4. The interface focuses on the can-do relationship type, while the abstract class focuses on the IS-A relationship;
5. Interface multi-definition object behavior; abstract class multi-definition object attributes;
6. The interface definition can use public, protected, internal, and private modifiers, but almost all interfaces are defined as public, so you don't have to say much about the reason.
7. "interface unchanged" is an important factor to consider. Therefore, when an extension is added by an interface, a new interface should be added instead of an existing interface.
8. Use the. NET Framework as an example. idisposable, idisposable, icomparable, iequatable, and ienumerable all have only one public method.
9. The upper-case letter "I" before the interface name is an agreement, just as it starts with an underscore below the field name. Stick to these principles.
10. All methods in the interface are public by default.
11. If a version issue is expected, you can create an "abstract class ". For example, if you have created a dog, a chicken, and a duck, you should consider abstracting the animal to deal with future things. Adding a new member to an interface requires you to modify all the derived classes and re-compile them. Therefore, it is best to use an abstract class to solve the version problem.
12. Non-abstract classes derived from abstract classes must include all the inherited abstract methods and the actual implementation of the abstract accessors.
13. The abstract class cannot use the new keyword or be sealed because the abstract class cannot be instantiated.
14. Static or virtual modifiers cannot be used in abstract method declarations.

 

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.