The difference between abstract class and interface

Source: Internet
Author: User

1. Introduction

2. Concept Introduction

What is an interface?

An interface is an abstract type that contains a set of virtual methods, each of which has its name, parameters, and return values. An interface method cannot contain any implementation, and the CLR allows an interface to contain events, properties, indexers, static methods, static fields, static constructors, and constants. However, note that C # cannot contain any static members. A class can implement multiple interfaces, and when a class inherits an interface, it not only implements all the methods defined by that interface, but also implements all the methods that the interface inherits from the other interfaces.

The definition method is:

The following is the referenced content:
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 as mode for transformational judgment
Testcls aCls = o as testcls;
if (aCls! = null)
{

Implementing an abstract method
Return _value.compareto (Acls._value);
}
}
}

What is an abstract class?

Abstract classes provide multiple derived classes that share a common definition of a base class that can provide either an abstract method or a non-abstract method. Abstract classes cannot be instantiated, and they must be implemented by derived classes to implement their abstract methods, so the new keyword cannot be used for abstract classes and cannot be sealed. If a derived class does not implement all of the abstract methods, the derived class must also be declared as an abstract class. In addition, the implementation of abstract methods is implemented by the overriding method.

The definition method is:

The following is the referenced content:
<summary>
Defining abstract Classes
</summary>
Abstract public class Animal
{
Defining static fields
static protected int _id;
Defining properties
public abstract static int Id
{
Get
Set
}


Defining methods
public abstract void Eat ();

Defining indexers
public string This[int i]
{
Get
Set
}
}

<summary>
Implementing abstract Classes
</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. Same points and different points

3.1 Identical points

cannot be instantiated directly, it is possible to implement its abstract method through inheritance.
Are the technical basis for abstract programming, and many design patterns have been realized.

3.2 Different points

Interfaces support multiple inheritance, and abstract classes cannot implement multiple inheritance.
An interface can only define abstract rules; an abstract class can define a rule and possibly provide an implemented member.
An interface is a set of behavior specifications; An abstract class is an incomplete class that focuses on the concept of a family.
Interfaces can be used to support callbacks, and abstract classes cannot implement callbacks because inheritance is not supported.
Interfaces contain only the signatures of methods, properties, indexers, events, but cannot define fields and methods that contain implementations; Abstract classes can define fields, properties, and methods that contain implementations.
Interfaces can be used for value types and reference types, and abstract classes can only be used for reference types. For example, a struct can inherit an interface and not inherit a class.

Through the same and different comparisons, we can only say that the interface and abstract classes, strengths, but no advantage. In the actual programming practice, we have to consider the specific circumstances to the discretion, but the following experience and accumulation, may give us some inspiration, in addition to some of my accumulation, many come from the classics, I believe that can withstand the test. So in the rules and occasions, we learn these classics, the most important thing is to apply, of course, I will opinion broad home smile, crossing please continue.

3.3 Rules and occasions

1. Keep in mind that one of the most important principles of object-oriented thinking is interface-oriented programming.
2. With the help of interfaces and abstract classes, many of the ideas in the 23 design patterns have been cleverly implemented, and I think the essence is simply: oriented toward abstract programming.
3. Abstract classes should be used primarily for closely related objects, and interfaces are best suited to provide common functionality for unrelated classes.
4. The interface focuses on the can-do relationship type, while the abstract class is biased to the is-a-type relationship;
5. Interface multi-definition object behavior, abstract class multi-definition object properties;
6. The interface definition can use public, protected, internal, and private modifiers, but almost all of the interfaces are defined as public, so there's no need to say more.
7. "Interface unchanged" is an important factor to be considered. Therefore, when an extension is added by an interface, the new interface should be added, and the existing interface cannot be changed.
8. As far as possible to design the interface into a single functional block, in the. NET framework, for example, IDisposable, IDisposable, IComparable, IEquatable, IEnumerable, and so on, all contain only one public method.
9. The capital letter "I" in front of the interface name is a convention, just as the field names begin with an underscore, adhere to these principles.
10. In the interface, all methods are default to public.
11. You can create an abstract class if you anticipate that a version problem will occur. For example, to create a dog, a chicken (Chicken), and a duck (Duck), you should consider abstracting the animal (Animal) to deal with the possible future of the wind horse cattle. Adding a new member to an interface would force the requirement to modify all derived classes and recompile, so the problem with versioning is best implemented as an abstract class.

12. A non-abstract class derived from an abstract class must include all inherited abstract methods and the actual implementation of the abstract accessor.
13. The New keyword cannot be used for abstract classes, nor can it be sealed, because abstract classes cannot be instantiated.
14. You cannot use the static or virtual modifier in an abstract method declaration.

The above rules, I will be brazen tentative for T14 bar, write so tired, as a temporary reward it. We can also exchange the exchange, I will revise it in time.

4. Classic example

4.1 Absolute Classics

The. NET Framework is the best resource for learning, and a conscious study of the FCL is a required course for every. NET programmer, and I have the following suggestions regarding the use of interfaces and abstract classes in the FCL:

1.FCL uses an interface-based design for the collection class, so please pay attention to the design implementation of the interface in System.Collections.
2.FCL uses abstract class-based design for the data flow related classes, so pay attention to the abstract class design mechanism of the System.IO.Stream class.

4.2 Different dishes

The following example, because it is my understanding, so give the classic "relative" mark, as to when the promotion to "absolute", just look at me. NET pursuit of the road, whether can as always so persistent, so I will be relatively reconstructed to absolute so far (hehe). This example does not describe the application of abstract classes and interfaces in design mode, because that will be another text of discussion value, this article focuses on the concepts and principles, but the real application comes from the specific requirements specification.

Design structure:

1. Defining abstract Classes

The following is the referenced content:
Public abstract class Animal
{
protected string _name;
Declaring abstract properties
Public abstract String Name
{
Get
}

Declaring abstract methods
public abstract void Show ();

Implementing a general approach
public void Makevoice ()
{
Console.WriteLine ("All animals can make voice!");
}
}

2. Defining the interface

The following is the referenced content:
public interface IAction
{
Define public method Labels
void Move ();
}

3. Implementing abstract classes and interfaces

The following is the referenced content:
public class Duck:animal, iaction
{
Public Duck (string name)
{
_name = name;
}
Overloaded abstract methods
public override void Show ()
{
Console.WriteLine (_name + "is showing for you.");
}

Overloading Abstract Properties
public override string Name
{
get {return _name;}
}

Implementing interface Methods
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

The following is the referenced content:

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. The Stone of his mountain

is the so-called truth is everyone to see, so the garden has an innovative point of view in this, one is to thank you for sharing, the second is to improve the opinion of the shortcomings, I hope to be able to form a knowledge of the field, be used for me, to be used in the public.


[url=]dunai[/url] That abstract classes are extracts of specific classes of common divisor, and interfaces are to "hash" some unrelated classes into a common group. As for their syntax in each language, the details of the language are not my main concern.
The collection of the Birch Mountain stream is also very good.
Artech that: The code is shared and extensible, so use the abstract Class as much as possible. Of course the interface in other aspects of the advantages, I think also can not be ignored.
Shenfx the use of interfaces when searching for functional commonalities among objects with large differences, and the use of abstract base classes when seeking functional differences among more common objects.

Finally, MSDN's recommendations are:

If you expect to create multiple versions of a component, create an abstract class. Abstract classes provide a simple way to control the component version. By updating the base class, all inherited classes are automatically updated with the changes. On the other hand, the interface cannot be changed once it is created. If a new version of the interface is required, a completely new interface must be created.
If you create a feature that will be used across a wide range of heterogeneous objects, the interface is used. Abstract classes should be used primarily for closely related objects, and interfaces are best suited to provide common functionality for unrelated classes.
If you want to design a small and concise function block, use the interface. If you are designing large functional units, use an abstract class.
Use an abstract class if you want to provide common, implemented functionality across all implementations of a component. Abstract classes allow partial implementations of classes, and interfaces do not contain implementations of any members.

6. Conclusion

interface and abstract class, is one of the most discussed topics on the forum and in the classroom, the reason for this old topic to come out again, is because from my experience, a deep understanding of these two object-oriented basic content, for the enliven object-oriented abstract programming idea is very important. This article basically outlines the interface and abstract class concepts, similarities and differences and the use of rules, from a learning point of view, I think these summaries are enough to express its core. But with an in-depth understanding of object-oriented and software design, and based on ongoing practice, Scott says that he insists on writing the demo one hours a day, so should we be more diligent about keyboards. For the interface and abstract class, please use it and know it, and think more about it.

The difference between abstract class and interface

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.