The article "Analysis of the importance of interfaces in C #" describes how to declare and use interfaces.
But C # has an abstract class that is formed by the abstract keyword, so how do we choose it?
C # allows classes and functions to be declared abstract. Abstract classes cannot be instantiated, and abstract functions cannot be implemented directly, and must be overridden in non-abstract derived classes. Obviously, the abstract function itself is virtual, but it can't provide the virtual keyword. If the class contains an abstract function, the class is also abstract and must be declared abstract.
To define an abstract class:
publicabstractclass Animal{ protectedstring _name; publicabstractstring Name { get; } publicabstractvoidShow(); publicvoidMakeVoice() { Console.WriteLine("All animals can make voice!"); }}
Define interfaces:
publicinterface IAction{ void Move();}
Implement abstract classes and interfaces:
Public classDuck:animal, iaction{ Public Duck(stringName) {_name = name; } Public Override void Show() {Console.WriteLine (_name +"is showing for you!"); } Public Override stringName {Get{return_name;} } Public void Move() {Console.WriteLine ("Duck also can swim."); }} Public classDog:animal, iaction{ Public Dog(stringName) {_name = name; } Public Override void Show() {Console.WriteLine (_name +"is showing for you!"); } Public Override stringName {Get{return_name;} } Public void Move() {Console.WriteLine (_name +"Duck also can run."); }}
Client implementations:
publicclass TestAnimal{ publicstaticvoidMain(string [] args) { new Duck("Duck"); duck.MakeVoice(); duck.Show(); new dog("Dog"); dog.MakeVoice; dog.Show(); new Dog("A big dog"); dogAction.Move(); }}
1. Abstract classes are common divisor that extract specific classes, and interfaces are intended to "hash" some unrelated classes into a common group.
2. All code is shared and extensible, using the abstract Class as much as possible.
3. Use an interface when looking for functional commonalities between objects with large differences, and use abstract classes when searching for functional differences among more common objects.
4. If you want to create multiple versions of a component, we recommend that you use an abstract class. If you design a small and concise function block, use the interface.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
An analysis of the differences between abstract classes and interfaces in C #