Sunny's Technology Blog

书山有路勤为径,学海无涯苦作舟

博客园 首页 新随笔 联系 订阅 管理

 

// inherit04.cs - Virtual Methods
//===============================================
using System;

class Person
{
    
protected string firstName;
    
protected string lastName;

    
public Person()
    
{
    }


    
public Person(string fn, string ln)
    
{
        firstName 
= fn;
        lastName 
= ln;
    }


    
public virtual void displayFullName()
    
{
        Console.WriteLine(
"{0} {1}", firstName, lastName);
    }
   
}


class Employee : Person 
{
    
public ushort hireYear;

    
public Employee() : base()
    
{
    }


    
public Employee(string fn, string ln, ushort hy) : base(fn, ln)
    
{
        hireYear 
= hy;
    }


    
public override void displayFullName()
    
{
        Console.WriteLine(
"Employee: {0} {1}", firstName, lastName);
    }
   
}


// A new class derived from Person
class Contractor : Person 
{
    
public string company;

    
public Contractor() : base()
    
{
    }


    
public Contractor(string fn, string ln, string c) : base(fn, ln)
    
{
        company 
= c;
    }


    
public override void displayFullName()
    
{
        Console.WriteLine(
"Contractor: {0} {1}", firstName, lastName);
    }
   
}


class NameApp 
{
    
public static void Main() 
    
{

        
//注意:在这里声明的是三个 Person 类型的变量,但是却用派生类来实例化了        
        Person Brad = new Person("Bradley""Jones");
        Person me   
= new Employee("Bradley""Jones"1983);
        Person Greg 
= new Contractor("Hill""Batfield""Data Diggers");
        
        
//他们实际调用的是派生类中的方法
        Brad.displayFullName();
        me.displayFullName();
        Greg.displayFullName();       
    }

}


运行结果:
Bradley Jones
Employee: Bradley Jones
Contractor: Hill Batfield
posted on 2005-08-15 15:22  Sunny  阅读(149)  评论(0)    收藏  举报