1. abstract methods
It can only be defined in an abstract class
Modifier measures can not be modified private virtual static
Abstract method is as follows:
public abstract class People //声明一个抽象类
{
public abstract void study(); //抽象方法只能定义在抽象类中。
}
public class Student:People //继承抽象类
{
public override void study() //重写抽象类的抽象方法
{
Console.WriteLine("好好学习,天天向上!");
}
}
public class Program
{
static void Main(string[] args)
{
Student t= new Student();//实例化派生类
People p= t; //使用派生类对象实例化抽象类
//以上两句等价于
//People p = new Student();//使用派生类对象实例化抽象类;
p.study(); //使用抽象类对象调用抽象类中的抽象方法study
}
}
to sum up:
(1) can only be declared abstract method in an abstract class, use the keyword abstract
(2) The abstract class abstract method must be overridden by subclasses .
[Abstract method is not a method thereof, a method thereof subclasses must override !!, abstract method thus can be seen as a virtual method is not the method body]
Virtual methods:
Modified using virtual methods:
Virtual method can be a method thereof. Specific examples are as follows:
public class BaseClass //创建一个基类
{
public virtual string GetName() //使用virtual关键字创建父类中的虚方法
{
return "父类虚方法体":
}
}
public class SubClass:BaseClass //子类继承父类
{
public override string GetName(); //子类重写父类虚方法
{
return "重写父类虚方法!";
}
}
Example above: virtual methods of the parent class is a derived class overrides.
Note: virtual modifier can not be used in conjunction with private, static, abstract, override modifier.
ps: override modifier and not new, static, virtual modifier used simultaneously, and only overridden method in the base class virtual method for rewriting.
Third, the difference between the two:
Summary: The abstract method is only a method name, there is no way the body (that is, no specific implementation method), subclass the parent class abstract method must be rewritten;
This method is a virtual function member has a method, but subclasses can cover, may not be covered.
(1) The method of virtual methods thereof, the method is not an abstract method thereof. Abstract method is a method of covering the derived class forced, or derived class can be instantiated;
(2) only abstract method declarations in an abstract class, not a virtual method;
(3) derived class must override the abstract method of the abstract class, a virtual method is not necessary.