Polymorphyism in C#

An example of failed polymorphyism

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class People
{
    public People(string Name = "Anonymous")
    {
        name = Name;
    }

    public string ShowInformation()
    {
        return string.Format("People(Name = {0})", name);
    }

    private string name;

    public string Name
    {
        set
        {
            name = value;
        }

        get
        {
            return name;
        }
    }
}

class Student : People
{
    public Student(string Name, string ID) : base(Name)
    {
        this.ID = ID;
    }

    new public string ShowInformation()
    {
        return string.Format("Student(Name = {0}, ID = {1})", this.Name, this.ID);
    }
    private string ID;
}

namespace Inheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            Student tom = new Student("Tom", "PB13233233");
            Console.WriteLine(tom.ShowInformation());
            People somebody = tom;
            Console.WriteLine(somebody.ShowInformation());
        }
    }
}

Corrected version

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class People
{
    public People(string Name = "Anonymous")
    {
        name = Name;
    }

    virtual public string ShowInformation()
    {
        return string.Format("People(Name = {0})", name);
    }

    private string name;

    public string Name
    {
        set
        {
            name = value;
        }

        get
        {
            return name;
        }
    }
}

class Student : People
{
    public Student(string Name, string ID) : base(Name)
    {
        this.ID = ID;
    }

    override public string ShowInformation()
    {
        return string.Format("Student(Name = {0}, ID = {1})", this.Name, this.ID);
    }
    private string ID;
}

namespace Inheritance
{
    class Program
    {
        static void Main(string[] args)
        {
            Student tom = new Student("Tom", "PB13233233");
            Console.WriteLine(tom.ShowInformation());
            People somebody = tom;
            Console.WriteLine(somebody.ShowInformation());
        }
    }
}
posted @ 2017-03-08 18:18  ch3cooh  阅读(169)  评论(0)    收藏  举报

Too young too simple. Sometimes naive! -- Quote from the elderly.