可以强制派生类覆盖基类的方法:将基类的方法声明为抽象的.为此,我们需要使用关键字abstract.抽象方法没有方法体,有派生类来提供.
当方法被声明为抽象的时,其所属的类也必须被声明为抽象的.
namespace ConsoleApplication1
{
abstract class Person
{
protected string firstName;
protected string lastName;
public Person()
{
}
public Person(string fn, string In)
{
firstName = fn;
lastName = In;
}
public abstract void displayFullname();
}
class Employee : Person
{
public ushort hireYear;
public Employee()
: base()
{ }
public Employee(string fn, string In, ushort hy)
: base(fn, In)
{
hireYear = hy;
}
public override void displayFullname()
{
Console.WriteLine("Employee:{0}{1}",firstName,lastName);
}
}
class Contractor : Person
{
public string company;
public Contractor()
: base()
{ }
public Contractor(string fn, string In, string c)
: base(fn, In)
{
company = c;
}
public override void displayFullname()
{
Console.WriteLine("Contractor:{0}{1}",firstName,lastName);
}
}
class NameApp
{
public static void Main()
{
Person me = new Employee("Bradley","Jones",1983);
Person Greg = new Contractor("Hill","Batfield","Data Diggers");
me.displayFullname();
Greg.displayFullname();
Console.Read();
}
}
}