为了更多地理解多态性,我构建了一个小测试,它返回了意想不到的结果。多态性意想不到的结果
所以这个想法是用虚拟/覆盖关键字覆盖基类的方法,但似乎我不需要这些?
public class Employee
{
public Employee()
{
this.firstName = "Terry";
this.lastName = "Wingfield";
}
public string firstName { get; set; }
public string lastName { get; set; }
public void writeName()
{
Console.WriteLine(this.firstName + " " + this.lastName);
Console.ReadLine();
}
}
public class PartTimeEmployee : Employee
{
public void writeName()
{
Console.WriteLine("John" + " " + "Doe");
Console.ReadLine();
}
}
public class FullTimeEmployee : Employee
{
public void writeName()
{
Console.WriteLine("Jane" + " " + "Doe");
Console.ReadLine();
}
}
static void Main(string[] args)
{
Employee employee = new Employee();
PartTimeEmployee partTimeEmployee = new PartTimeEmployee();
FullTimeEmployee fullTimeEmployee = new FullTimeEmployee();
employee.writeName();
partTimeEmployee.writeName();
fullTimeEmployee.writeName();
}
}
利用上述我期待的代码导致像这样:
- 特里Wignfield
- 特里温菲尔德
- 特里温菲尔德
但代替下面被写入到控制台:
- 特里温菲尔德
- 李四
- 李四
我认为后者是行不通的,因为这将所需要的ovrride关键字。
所以问题是为什么我看到没有适当的关键字后面的名字?
我希望这是足够清晰的阅读。
问候,
这是因为'writeName()'的子类是_hiding_基类的版本(你应该已经看到了编译器警告这个)。如果你把所有三个都投入到'员工'中,你应该看到第一个结果。 – JLRishe 2014-08-27 13:51:48
@JLRishe非常感谢你的赞赏。 – 2014-08-27 18:41:13