C # class, interface, virtual method, and abstract method-similarities and differences between abstract classes and interfaces

Source: Internet
Author: User

Reprinted from http://hi.baidu.com/sjjqaa2010/blog/item/963bd13e0cdcadf33c6d974a.html

 

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:

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:

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.

3. abstract classes and interfaces
similarities:
(1) Both can be inherited
(2) none of them can be instantiated
(3) both can contain the method declaration
(4) A derived class must implement an unimplemented method
area:
(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. Abstract classes can define variables, but interfaces cannot.
(2) an abstract class is an incomplete class and needs to be further refined. The interface is 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) interfaces can be implemented in multiple ways, and abstract classes can only be inherited in a single way.
(4) abstract classes are defined in a series of closely related classes, in most of the classes whose interfaces are loose but all implement a certain function,
(5) abstract classes are abstract concepts from a series of related objects, therefore, it reflects the internal commonality of things. interfaces are a functional Convention defined to satisfy external calls, so they reflect the external characteristics of things
(6) basically, an interface does not have any specific characteristics of inheritance. It only promises methods that can be called.
(7) an interface can be used to support callback, inheritance does not have this feature.
(8) the specific methods implemented by the abstract class are virtual by default, but the interface methods in the class implementing the interface are non-virtual by default, of course, you can also declare it as virtual
(9) If an abstract class implements an interface, you can map the methods in the interface to the abstract class as an abstract method without having to implement it, implement Methods in the interface in the subclass of the abstract class

usage rules:
1. abstract classes are mainly used for closely related objects, interfaces are most suitable for providing general functions for unrelated classes
2. If you want to design a large function unit, use an abstract class. If you want to design a small and concise function block, the interface is used.
3. If multiple versions of a component are expected to be created, an abstract class is created. 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, the abstract class is used.
5. Analyze objects and extract internal commonalities to form abstract classes to indicate the object nature, that is, "What ". Interface is preferred for external calls or functions that need to be extended
6. A good interface definition should have specific functionality rather than multiple functions, 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 function, instead, black box multiplexing is used, 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 another class. This is a very basic design principle.
for example:
the window form can be designed using abstract classes. Public operations and attributes can be put in an abstract class so that the form and dialog box can inherit from this abstract class, then, expand and improve according to your 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 as required. You can call this function only through the interface, instead of printing the form.

4. OthersArticle
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 child classes and improvesCodeThis 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:

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:

interfaces are used to find 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 that the most important principle 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. In my opinion, the essence is simply abstract programming.
3. abstract classes are 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. behavior of Multi-definition objects in interfaces; Attributes of Multi-definition objects in abstract classes;
6. interface definitions 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. NET Framework as an example. idisposable, idisposable, icomparable, iequatable, and ienumerable all have only one public method.
9. The upper-case letter "I" in front of the interface name is an agreement. Stick to these principles, just as the name starts with an underscore.
10. In the interface, all methods are public by default.
11. If a version problem 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. abstract classes cannot use the new keyword or be sealed because they cannot be instantiated.
14. Static or virtual modifiers cannot be used in abstract method declarations.

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.