Selection of abstract classes and interfaces

Source: Internet
Author: User
Tags define abstract
Abstract base classes and interfaces, selection of commonalities and personalities

Abstract Class and Interface in C # both implement the Inheritance Mechanism in object orientation, they define abstract methods to uniformly implement functional constraints on the inheritance class, so how to select an appropriate Inheritance Mechanism in an appropriate scenario is a problem we often encounter in the design, let's first compare the differences and relationships between the two.

Similarities

  • Can be inherited.
  • Cannot be instantiated.

Differences

  • Abstract classes are incomplete classes and need to be further refined. interfaces are just behavioral specifications.
  • Abstract base classes cannot implement multi-inheritance, while interfaces can implement multi-inheritance.
  • Abstract base classes can define fields, attributes, and include implementation methods. The interface can define fields, indexers, events, but cannot define fields and include implementation methods.

Commonalities, personalities, and choices

In some books, we recommend using interfaces to replace Abstract classes in C # and emphasize the 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. Different personalities share the same behavior.
  3. The implementation of the same behavior is quite different.

The design is as follows: Well, now we will give you three objects, namely, carp, carp, and goldfish, which still allow you to design base classes 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:

1 interface ISwim
2 {
3 void Swim ();
4}
5
6 public class Person: ISwim
7 {
8 public void Swim ()
9 {
10 // specify Ming in person's style.
11}
12}
13
14 public class Frog: ISwim
15 {
16 public void Swim ()
17 {
18 // specify Ming in frog's style.
19}
20}
21
22 public class Fish: ISwim
23 {
24 public void Swim ()
25 {
26 // specify Ming in fish's style.
27}
28}

 

  1. Commonality is greater than individuality
  2. Individuals with the same commonalities must have the same attributes and behaviors.
  3. The implementation methods of the same behavior are different.

Designed:Summary:

1 abstract public class Fish
2 {
3 abstract public void Swim ();
4}
5
6 public class carp: Fish
7 {
8 public override void Swim ()
9 {
10 // Swim like a catfish
11}
12}
13
14 public class carp: Fish
15 {
16 public override void Swim ()
17 {
18 // Swim like a carp
19}
20}
21
22 public class goldfish: Fish
23 {
24 public override void Swim ()
25 {
26 // Swim like a goldfish
27}
28}

 

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 separating interfaces from abstract base classes is as follows:

  1. Use interfaces when looking for functional commonalities between objects with large differences.
  2. Abstract base classes are used when looking for functional differences between objects with many commonalities.

Summary of differences between abstract classes and interfaces

1. Classes are abstract objects. abstract classes can be interpreted as classes as objects and abstracted into classes.
An interface is just a behavior specification or provision. Microsoft's custom interface always carries the able field to prove that it represents a class of "I can do it ...". 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.
2. The interface basically does not have any specific characteristics of inheritance. It only promises the methods that can be called;
3. A class can implement several interfaces at a time, but only one parent class can be extended.
4. interfaces can be used to support callback, but inheritance does not.
5. the abstract class cannot be sealed.
6. 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 virtual.
7. Similar to a non-abstract class, an abstract class must also provide its own implementation for all the members of the interface listed in the base class list of this class. However, the abstract class is allowed to map interface methods to abstract methods.
8. abstract classes implement a principle in oop, namely, separating mutable from immutable. Abstract classes and interfaces are defined as immutable classes and can be implemented as subclasses.
9. A good interface definition should be specific and functional, rather than multi-functional, otherwise it will 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.
10. 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.
11. 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. Instead, you can implement the interface method in the subclass of the abstract class;
• If multiple versions of a component are expected to be created, an abstract class is created. Abstract classes provide simple methods to control component versions.
• If the created function is used across a wide range of different objects, the interface is used.
• Use interfaces to design small and concise functional blocks. 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 class:
A. classes that contain one or more abstract methods or attributes must be defined as abstract classes.
B. The derived class that inherits the abstract class must implement all abstract methods or attributes of the abstract class. Otherwise, the derived class must also be an abstract class until it is fully implemented.
C. The abstract class must be public ).
D. The abstract class does not have an object instance, but can declare to reference the variable. In addition, the abstract class can have non-Abstract methods for the derived class to call.

Port:
1. define abstract methods, attributes, indexes, and events in Interfaces
2. The interface must be implemented by the class, so it can only be public by default. It cannot be declared as static.
3. The class that implements the interface must fully implement all the method attributes, indexes, and events in the interface.
4. A class can only inherit one base class, but multiple interfaces can be implemented. The inherited base class must be placed at the beginning, followed by an interface, which can be separated by teasing.

========================================================== ========================================================== =

When are abstract classes and interfaces used?

※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.
※Abstract classes are used to provide common implemented functions among all components. Abstract classes allow partial implementation classes, while interfaces do not include the implementation of any member.

========================================================== ========================================================== =

1. interfaces can only contain methods and fields. abstract classes can contain methods or attributes and fields;
2. Methods in interfaces do not need to be implemented, but abstract classes can have implemented methods;
3. interfaces can replace multiple inheritance to some extent.
4. Implementing interfaces means that all methods in interfaces must be implemented. If you inherit the subclass or abstract class of an abstract class, you can only implement some methods.
5. interfaces and abstract classes are not converted into objects by instances.

========================================================== ========================================================== =

First, you must clarify the differences between abstract classes and Interface Usage. classes can only be inherited in a single way. If a class method is implemented only by its derived classes, you can use abstract classes, if the method is used by multiple classes, the interface is used.
For example:
Use abstract classes:
Abstract class
{
Abstract public void put ();
}

Class B:
{
Public void put ()
{
Console. WriteLine ("B ");
}
}

//-----------------------------------------

Interface:
Interface Ia
{
Public void put ();
}
 
Class A: Ia
{
Public void put ()
{
Console. WriteLine ("");
}
}
 
Class B: Ia
{
Public void put ()
{
Console. WriteLine ("B ");
}
}

========================================================== ========================================================== =

 The following is a detailed comparison between abstract classes and interfaces.

Abstract method) Interface)
Can contain implementation Blocks Cannot contain implementation Blocks
Can contain abstract methods Cannot contain abstract methods
Can contain non-public members It cannot contain non-public members.
Can inherit other classes, including non-abstract classes Can inherit other interfaces
Controllable version Version cannot be controlled
Cannot be instantiated Cannot be instantiated

========================================================== ========================================================== =

Interface is used to define the contract between two objects. abstract classes are used to encapsulate the common behavior between objects.
The two are completely different in their initial design goals. Unfortunately, they are misunderstood by too many people in practical applications.

Interface-rough Technical Specifications
Abstract class-a rough description of technical specifications
Class-specific implementation of technical specifications

========================================================== ========================================================== =

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.