调用重写方法

时间:2016-09-30 22:42:37

标签: c#

下面显示了我的3个课程:PersonEmployeeSalaryEmployee

每个类(从右侧)继承左侧的类。例如:SalaryEmployee继承自Employee

class Person
{
    private string address;
    private string name;

    public Person(string givenName, string givenAddress)
    {
        name = givenName;
        address = givenAddress;
    }

    public virtual void outputName()
    {
        MessageBox.Show("My name is " + name);
    }

    public void outputAddress()
    {
        MessageBox.Show("My address is " + address);
    }

    public void setName(string newName)
    {
        name = newName;
    }

    public void setAddress(string newAddress)
    {
        address = newAddress;
    }
}

class Employee : Person
{
    private string NINumber;

    public Employee(string givenName, string givenAddress) : base(givenName, givenAddress)
    {
    }

    public void setNINumber(string givenNumber)
    {
        NINumber = givenNumber;
    }

    public void getNINumber()
    {
        MessageBox.Show("My National Insurance Number is " + NINumber);
    }
}

class SalaryEmployee : Employee
{
    private string name;
    private string address;

    public SalaryEmployee(string givenName, string givenAddress) : base(givenName, givenAddress)
    {
        name = givenName; address = givenAddress;
    }

    public override void outputName()
    {
        MessageBox.Show("My name is " + "S_" + name);  
    }
}
对我来说OOP相当新,我试图获得继承权。我面临的问题是我创建了一个名为'PersonFive'的对象:

SalaryEmployee personFive = new SalaryEmployee("Bob", "North Pole");

//忽略我用作参数的地址'北极',它仅用于此示例。

我可以调用.outputName()方法,输出将是:

"My name is Bob"

但是,调用基本方法而不是重写方法。我希望它给我的输出是“我的名字是S_Bob”

1 个答案:

答案 0 :(得分:0)

它为我工作,你可能没有发布导致错误的实际代码。

The code output