using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestE
{
class Employee
{
public string _name;
public Employee(string name)
{
this._name = name;
Console.Write ("Employee.CalculatePay:\n\t");
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.Write ("SalariedEmployee.CalculatePay:\n\t");
CalculatePay ();
}
public override void CalculatePay()
{
Console.WriteLine ("{0}, SalariedEmployee.CalculatePay, 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:\n\t");
this.CalculatePay ();
}
public override void CalculatePay()
{
Console.WriteLine ("{0}, ContractEmployee.CalculatePay, salary={1:C}", _name, _rate);
}
}
class Program {
static void Main(string[] args)
{
Employee[] employee = new Employee[2];
employee[0] = new ContractEmployee("Ada" +
"m Barr", 123.45);
Console.WriteLine ("");
employee[1] = new SalariedEmployee(
"Max Benson", 67890m);
}
}
}
c++ 과는 다른 결과를 보인다, 생성자가 호출된 클래싀의 함수가 불리지 않고 virtual 로 선언된 경우 자식 함수가 불리게 된다
Employee.CalculatePay:
Adam Barr, ContractEmployee.CalculatePay, salary=₩0
ContractEmployee.CalculatePay:
Adam Barr, ContractEmployee.CalculatePay, salary=₩123
Employee.CalculatePay:
Max Benson, SalariedEmployee.CalculatePay, salary=₩0
SalariedEmployee.CalculatePay:
Max Benson, SalariedEmployee.CalculatePay, salary=₩67,890
'프로그래밍(Programming) > C#' 카테고리의 다른 글
[c#]class 앞에 붙는 public 이란? (0) | 2015.08.28 |
---|---|
[C#]정적 생성자(static constructor) (0) | 2015.08.28 |
[C#] 상속받은 후 new , override 차이점 예제 (0) | 2015.08.27 |
[C#] 'Checked', 'unchecked' 키워드 (0) | 2015.08.27 |
C# Boxing과 Unboxing 의 내부 처리 (0) | 2015.08.26 |