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:
public abstract class Animal{ protected string _name; public abstract string Name { get; } public abstract void Show(); public void MakeVoice() { Console.WriteLine("All animals can make voice!"); }}
Define interfaces:
public interface IAction{ void Move();}
Implement abstract classes and interfaces:
PublicClass Duck:animal, iaction{PublicDuck (String name) {_name = name;}PublicOverridevoidShow () {Console.WriteLine (_name +"is showing for you!"); }PublicOverrideString Name {get{return _name;} }PublicvoidMove () {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 + "Duck also can run.");}
Client implementations:
public class TestAnimal{ 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(); }}
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.
An analysis of the differences between abstract classes and interfaces in C #