using System;
using System.Text;
//基类
class Person
{
protected string firstName;
protected string middleName;
protected string lastName;
private int age;
public Person()
{
}
public Person(string fn, string ln)
{
firstName = fn;
lastName = ln;
}
public Person(string fn, string mn, string ln)
{
firstName = fn;
middleName = mn;
lastName = ln;
}
public Person(string fn, string mn, string ln, int a)
{
firstName = fn;
middleName = mn;
lastName = ln;
age = a;
}
public void displayAge()
{
Console.WriteLine("Age {0}", age);
}
public void displayFullName()
{
StringBuilder FullName = new StringBuilder();
FullName.Append(firstName);
FullName.Append(" ");
if( middleName != "" )
{
FullName.Append(middleName[0]);
FullName.Append(". ");
}
FullName.Append(lastName); 
Console.WriteLine(FullName);
}
}
//下面的类要继承基类
class Employee : Person
{
private ushort hYear;
public ushort hireYear
{
get { return(hYear); }
set { hYear = value; }
}
public Employee() : base()
{
}
public Employee( string fn, string ln ) : base( fn, ln)
{
}
public Employee(string fn, string mn, string ln, int a) :
base(fn, mn, ln, a)
{
}
public Employee(string fn, string ln, ushort hy) : base(fn, ln)
{
hireYear = hy;
}
//覆盖基类的方法
public new void displayFullName()
{
Console.WriteLine("Employee: {0} {1} {2}",
firstName, middleName, lastName);
}
}
class NameApp
{
public static void Main()
{
Person myWife = new Person("Melissa", "Anne", "Jones", 21);
Employee me = new Employee("Bradley", "L.", "Jones", 23);
Employee you = new Employee("Kyle", "Rinni", 2000);
myWife.displayFullName();
myWife.displayAge();
me.displayFullName();
Console.WriteLine("Year hired: {0}", me.hireYear);
me.displayAge();
you.displayFullName();
Console.WriteLine("Year hired of him: {0}", you.hireYear);
you.displayAge();
}
}
可以将一个派生类的对象赋给基类对象
using System;
class Person
{
protected string firstName;
protected string lastName;
public Person()
{
}
public Person(string fn, string ln)
{
firstName = fn;
lastName = ln;
}
public void displayFullName()
{
Console.WriteLine("{0} {1}", firstName, lastName);
}
}
class Employee : Person
{
public ushort hireYear;
public Employee() : base()
{
}
public Employee( string fn, string ln ) : base( fn, ln)
{
}
public Employee(string fn, string ln, ushort hy) : base(fn, ln)
{
hireYear = hy;
}
public new void displayFullName()
{
Console.WriteLine("Employee: {0} {1}", firstName, lastName);
}
}
class NameApp
{
public static void Main()
{
Employee me = new Employee("Bradley", "Jones", 1983);
Person Brad = me;
me.displayFullName();
Console.WriteLine("Year hired: {0}", me.hireYear);
Brad.displayFullName();
}
}


浙公网安备 33010602011771号