第四部分 方法4---------------

从构造器调用虚拟方法

    当我们实例化一个派生的SalariedEmployee对象时,运行的第一个构造器是基本的Employee构造器,它调用派生的SalariedEmployee.CaluculatePay 方法.但是,这个调用发生在派生的SalariedEmployee构造器之前.因此,附加的SalariedEmployee字段还没有被初始化:

using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  csharpMethod
{
    
class Employee
    
{
        
public string name;
        
public Employee(string name)
        
{
            
this.name = name;
            Console.Write(
"Employee.CalculatePay: ");
            CalculatePay();
        }

        
public virtual void CalculatePay()
        
{
            Console.WriteLine(
"Employee.CalculatePay called for {0}", name);

        }

    }

    
class SalariedEmployee : Employee
    
{
        
public decimal salary;
        
public SalariedEmployee(string name, decimal salary)
            : 
base(name)
        
{
            
this.salary = salary;
            Console.WriteLine(
"SalariedEmployee.CalculatePay: ");
            CalculatePay();
        }

        
public override void CalculatePay()
        
{
            Console.WriteLine(
"{0},SalariedEmployee,salary={1:C}", name, salary);

        }

    }

    
class ContractEmployee : Employee
    
{
        
public double rate;
        
public ContractEmployee(string name, double rate)
            : 
base(name)
        
{
            
this.rate = rate;
            Console.Write(
"ContractEmployee.CalculatePay: ");
            CalculatePay();

        }

        
public override void CalculatePay()
        
{
            Console.WriteLine(
"{0},SalariedEmployee,salary={1:C}", name, rate);
        }

    }

    
    
class Test
    
{
        
protected Employee[] employees;
        
static void Main(string[] args)
        
{
            Employee[] employees 
= new Employee[2];
            employees[
0= new ContractEmployee("Adam Barr"123.45);
            employees[
1= new SalariedEmployee("Max Benson", 67890m);
        }

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值