(50分)求一个类要用到多态和重载!
请给出代码实例,体现一个类其中要用到多态和重载。 --------------------编程问答-------------------- 此示例定义了一个名为 Employee 的基类,和一个名为 SalesEmployee 的派生类。SalesEmployee 类包括一个额外的属性 salesbonus,并重写方法 CalculatePay 以便将该属性考虑在内。using System;
class TestOverride
{
public class Employee
{
public string name;
// Basepay is defined as protected, so that it may be
// accessed only by this class and derrived classes.
protected decimal basepay;
// Constructor to set the name and basepay values.
public Employee(string name, decimal basepay)
{
this.name = name;
this.basepay = basepay;
}
// Declared virtual so it can be overridden.
public virtual decimal CalculatePay()
{
return basepay;
}
}
// Derive a new class from Employee.
public class SalesEmployee : Employee
{
// New field that will affect the base pay.
private decimal salesbonus;
// The constructor calls the base-class version, and
// initializes the salesbonus field.
public SalesEmployee(string name, decimal basepay,
decimal salesbonus) : base(name, basepay)
{
this.salesbonus = salesbonus;
}
// Override the CalculatePay method
// to take bonus into account.
public override decimal CalculatePay()
{
return basepay + salesbonus;
}
}
static void Main()
{
// Create some new employees.
SalesEmployee employee1 = new SalesEmployee("Alice",
1000, 500);
Employee employee2 = new Employee("Bob", 1200);
Console.WriteLine("Employee " + employee1.name +
" earned: " + employee1.CalculatePay());
Console.WriteLine("Employee " + employee2.name +
" earned: " + employee2.CalculatePay());
}
}
--------------------编程问答-------------------- 楼上正解 --------------------编程问答-------------------- 怎么都在用这个例子啊! --------------------编程问答-------------------- 教材嘛 --------------------编程问答-------------------- namespace ConsoleApplication1
{
public class A
{
public virtual void Fun1(int i)
{
System.Console.WriteLine(i);
}
public void Fun2(A a)
{
a.Fun1(1);
Fun1(5);
}
}
public class B : A
{
public override void Fun1(int i)
{
base.Fun1(i + 1);
}
public static void Main()
{
A a = new A();
A b = new B();
a.Fun2(a);
b.Fun2(b);
}
}
}
程序运行结果 --------------------编程问答-------------------- up
补充:.NET技术 , ASP.NET