Content source <You must know. Net>
Title: Object-oriented programming: interfaces and abstract classes
Time: 2008-09-11
Content:
Concept:
1. Interface-an interface is an abstract type that contains a set of virtual methods. Each method has its name, return type, and parameter. An interface method cannot contain any implementation;
When a class can implement multiple interfaces, it not only needs to implement all methods of the interface, but also all methods that implement the interface inherited from other interfaces.
2. abstract class -- abstract class provides public definitions of shared classes for multiple Derived classes. It can provide abstract methods or non-abstract methods. Abstract classes cannot be instantiated;
Cannot 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 abstract Method
Override method to complete;
Sample Code:
1. define abstract classes
Code
1 Abstract Public class animal
2 {
3 protected string _ name;
4 // declare abstract attributes
5 Abstract Public string name
6 {
7 get;
8}
9 // declare an abstract Method
10 Abstract Public void show ();
11 // General Implementation Method
12 public void makevoice ()
13 {
14 console. writeline ("all animal can make voice! ");
15}
16}
2. Define Interfaces
Code
1 public interface iaction
2 {
3 // define public methods
4 void move ();
5}
3. Implement abstract classes and interfaces
Code
// Dock class
Public class Duck: Animal, iaction
{
// Constructor
Public duck (string name)
{
_ Name = Name;
}
// Overload the abstract Method
Public override void show ()
{
Console. writeline (_ name + "is showing for you! ");
}
// Overload abstract attributes
Public override string name
{
Get {return _ name ;}
}
// Interface Implementation Method
Public void move ()
{
Console. writeline ("duck also can swim! ");
}
}
// Dog class
Public class Dog: Animal, iaction
{
// Constructor
Public dog (string name)
{
_ Name = Name;
}
// Overload abstract attributes
Public override string name
{
Get {return _ name ;}
}
// Overload the abstract Method
Public override void show ()
{
Console. writeline (_ name + "can run! ");
}
// Interface Implementation Method
Public void move ()
{
Console. writeline (_ name + "is showing for you! ");
}
}
4. Client call
Code
1 public class testanmial
2 {
3 Public static void main (string [] ARGs)
4 {
5 animal duckobj = new duck ("Duck ");
6 duckobj. Show ();
7 duckobj. makevoice ();
8
9 animal dogobj = new dog ("dog ");
10 dogobj. Show ();
11 dogobj. makevoice ();
12}
13}
Result:
Duck is showing for you!
All animal can make voice!
Dog can run!
All animal can make voice!