Abstract what is the difference between class and interface? (2)

Source: Internet
Author: User
Tags define abstract

1. Introduction

In my previous post titled "who is the abstract class and interface?", I discussed with my colleague Guan Wei and got the attention of many friends, because it is not a systematic theory, this makes it inconvenient for you to understand.
I think it is also necessary to make a summary of the systemic theory of this topic, so this article is coming soon. At the same time, I will also explain the problems mentioned above.

2. introduction of concepts

● What is an interface?

An interface is an abstract type that contains a set of virtual methods. Each method has its name, parameter, and return value. Interface methods cannot contain any implementations. CLR allows interfaces to include events, attributes, and indexes.
Static Method, static field, static constructor, and constant. Note: C # cannot contain any static members. A class can implement multiple interfaces. When a class inherits an interface, it must not only implement
All methods defined by this interface must also implement all methods inherited from other interfaces.

Definition method:

Reference content is as follows:
Public interface system. icomparable
{
Int compareto (Object O );
}
Public class testcls: icomparable
{
Public testcls ()
{
}

Private int _ value;
Public int Value
{
Get {return _ value ;}
Set {_ value = value ;}
}

Public int compareto (Object O)
{

// Use the as mode for transformation judgment
Testcls ACLs = O as testcls;
If (ACLs! = NULL)
{

// Implement the abstract Method
Return _ value. compareto (ACLs. _ value );
}
}
}

● What is an abstract class?

Abstract classes provide multiple Derived classes that share the public definitions of the base class. They can provide both abstract methods and non-abstract methods. An abstract class cannot be instantiated. It must be inherited by a derived class to implement its abstract method,
Therefore, the abstract class cannot use the new keyword or be sealed. If the derived class does not implement all abstract methods, the derived class must also be declared as an abstract class. In addition, the abstract Method
Overriding method.

Definition method:

Reference content is as follows:
/// <Summary>
/// Define an abstract class
/// </Summary>
Abstract Public class animal
{
// Define static Fields
Static protected int _ id;
// Define attributes
Public abstract static int ID
{
Get;
Set;
}

// Define the Method
Public abstract void eat ();

// Define the Indexer
Public String This [int I]
{
Get;
Set;
}
}

/// <Summary>
/// Implement an abstract class
/// </Summary>
Public class Dog: Animal
{
Public static override int ID
{
Get {return _ id ;}
Set {_ id = value ;}
}

Public override void eat ()
{
Console. Write ("Dog eats .")
}
}

3. Similarities and Differences

3.1 similarities

● They cannot be directly instantiated. They can all be inherited to implement their abstract methods.
● It is the technical basis for abstract programming and implements many design modes.

3.2 differences

● Interfaces support multi-inheritance; abstract classes cannot implement multi-inheritance.
● An interface can only define abstract rules. An abstract class can either define rules or provide implemented members.
● An interface is a set of behavioral norms; an abstract class is an incomplete class that focuses on the concept of a family.
● Interfaces can be used to support callback. abstract classes cannot implement callback because inheritance is not supported.
● An interface only contains methods, attributes, indexers, and event signatures, but cannot define fields or methods that contain implementations. An abstract class can define fields, attributes, and methods that have implementations.
● The interface can act on the Value Type and reference type; the abstract class can only act on the reference type. For example, struct can inherit interfaces rather than classes.

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, but the following experiences and accumulation, or
May give you some inspiration. In addition to some of my accumulation, many of them come from the classic, and 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.
With the words of the family, you can continue watching the official website.

3.3 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, consider Abstracting an animal.
(Animal. 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.

The above rules are tentatively set to T14. If I am so tired of writing, I will be rewarded for the moment. You can also contact each other. I will revise it in time.

4. Classic example

4.1 Absolute classic

. NET Framework is the best resource for learning. Conscious Research of FCL is a required course for every. Net programmer. I have the following suggestions on the use of interfaces and abstract classes in FCL:

1. FCL uses an interface-based design for the Collection class. Therefore, pay attention to the interface design and implementation in system. collections;
2. FCL uses Abstract class-based design for Data Stream-related classes. Therefore, pay attention to the abstract class design mechanism of the system. Io. Stream class.

4.2 special dishes

The following example marks the classic as "relative" because of my understanding. As for when to be promoted to "absolute", I am here. is it true that, as always
So I will reconstruct the relative structure to the absolute end (haha ).
This example does not describe the application of abstract classes and interfaces in the design mode, because it will be another valuable text to be discussed. This article focuses on understanding concepts and principles, but the real application comes from specific requirements and specifications.

Design structure:

1. define abstract classes

Reference content is as follows:
Public abstract class animal
{
Protected string _ name;
// Declare abstract attributes
Public abstract string name
{
Get;
}

// Declare the abstract Method
Public abstract void show ();

// General Implementation Method
Public void makevoice ()
{
Console. writeline ("all animals can make voice! ");
}
}

2. Define Interfaces

Reference content is as follows:
Public interface iaction
{
// Define public method labels
Void move ();
}

3. Implement abstract classes and interfaces

Reference content is as follows:
Public class Duck: Animal, iaction
{
Public duck (string name)
{
_ Name = Name;
}
// Overload the abstract Method
Public override void show ()
{
Console. writeline (_ name + "is showing for you .");
}

// Overload abstract attributes
Public override string name
{
Get {return _ name ;}
}

// Interface Implementation Method
Public void move ()
{
Console. writeline ("duck also can swim .");
}

}

Public class Dog: Animal, iaction
{
Public dog (string name)
{
_ Name = Name;
}

Public override void show ()
{
Console. writeline (_ name + "is showing for you .");
}

Public override string name
{
Get {return _ name ;}
}

Public void move ()
{
Console. writeline (_ name + "also can run .");
}

}

4. Client implementation

Reference content is as follows:

Public class testanmial
{
Public static void main (string [] ARGs)
{
Animal duck = new duck ("Duck ");
Duck. makevoice ();
Duck. Show ();

Animal dog = new dog ("dog ");
Dog. makevoice ();
Dog. Show ();

Iaction dogaction = new dog ("a big dog ");
Dogaction. Move ();
}
}

5. other mountains and stones

The so-called truth is what we have seen, so we can list innovative ideas in the garden here. One is to thank everyone for sharing, and the other is to improve the words of the family, I hope that I can build knowledge in the field, use it for me, and use it for the public.

● [Url =] dunai [/url]: abstract classes are used to extract the common expression of a specific class, while interfaces are used to generate irrelevant classes into a common group. As for their syntaxes in various languages, language details are not my focus.
● The collection of Hua Shan Jian is also very good.
● Artech believes that abstract class should be used whenever possible for code sharing and scalability. Of course, the advantages of interfaces in other aspects cannot be ignored.
● Shenfx believes that interfaces are used when looking for functional commonalities between objects with large differences. When looking for functional differences between objects with large differences, use abstract base classes.

Finally, the msdn suggestions are as follows:

● If multiple versions of a component are expected to be created, an abstract class is created. Abstract classes provide a simple way to control component versions. By updating the base class, all inheritance classes are automatically updated with the change. On the other hand, the interface cannot be changed once it is created. If you need a new version of the interface, you must create a new interface.
● If the created function is used across a wide range of different objects, the interface is used. Abstract classes are mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.
● If you want to design small and concise functional blocks, use interfaces. If you want to design a large functional unit, use an abstract class.
● If you want to provide common implemented functions among all the implementations of a component, use an abstract class. Abstract classes allow partial implementation classes, while interfaces do not include the implementation of any member.

6. Conclusion

Interfaces and abstract classes are one of the most discussed topics on the Forum and in the classroom. The reason why I discuss this old topic is that from my experience, deeply understand the basic content of these two object-oriented systems,
It is vital to revitalize the object-oriented abstract programming ideology. This article gives a basic overview of the concepts, similarities and use rules of interfaces and abstract classes. From a learning point of view, I think these summaries are sufficient to express their core.
However, the deep understanding of object-oriented and software design is based on continuous practice. Scott said that he insisted on writing a demo every day for an hour. Should we be more diligent in keyboard?
And. For interfaces and abstract classes, please use them for more information.

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.