This article introduces the following:
• Object-oriented Thinking: Polymorphism
• Interface
• Abstract class
1. Introduction
In my previous post "html"> who is the abstract class and interface? ", I discussed it with my colleague Guan Wei and got the attention of many friends, because it is not a systematic theory, therefore, it is inconvenient for everyone to understand. At the same time, I think it is also necessary to summarize the systemic theory of this topic. Therefore, this article has been released. At the same time, I will also explain the problems mentioned above.
2. introduction of concepts
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, indexers, static methods, static fields, static constructors, and constants. 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, but also implement all methods inherited from other interfaces.
Definition method:
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 Abstract METHODS
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. Abstract classes cannot be instantiated. They must be inherited by the derived classes to implement their abstract methods. Therefore, abstract classes 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 overriding method is used to implement the abstract method.
Definition method:
/// <Summary>
/// Define abstract classes
/// </Summary>
Abstract Public Class Animal
{
// Define static Fields
Protected Int _ Id;
// Define attributes
Public Abstract Int Id
{
Get ;
Set ;
}
// Definition Method