1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 9. OOP - Polymorphism


Lesson Objective

  • Understand Polymorphism.

Lesson Notes

Polymorphism

Polymorphism, which translates to "many forms," arises when we have multiple classes connected through inheritance.

Inheritance enables the acquisition of attributes and methods from another class.

Polymorphism, in turn, utilizes these inherited methods to carry out alternate but similar tasks. This flexibility permits the execution of a single action in different ways.

Main.c#

public class Student
{
    private string name;
    private int age;

    public Student(string n, int a)
    {
        name = n;
        age = a;
    }

    public void ValidAge()
    {
        if (age >= 11 && age <= 16)
        {
            Console.WriteLine("Age Valid");
        }
        else
        {
            Console.WriteLine("Age Invalid");
        }
    }

    public string GetName()
    {
        return name;
    }

    public void SetName(string n)
    {
        name = n;
    }

    public int GetAge()
    {
        return age;
    }

    public void SetAge(int a)
    {
        age = a;
    }
}

public class P16_Student : Student
{
    private bool ucas;

    public P16_Student(string n, int a, bool u) : base(n, a)
    {
        ucas = u;
    }

    public override void ValidAge()
    {
        if (base.GetAge() >= 16 && base.GetAge() <= 19)
        {
            Console.WriteLine("Age Valid");
        }
        else
        {
            Console.WriteLine("Age Invalid");
        }
    }

    public bool GetUCAS()
    {
        return ucas;
    }

    public void SetUCAS(bool u)
    {
        ucas = u;
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        P16_Student stu24 = new P16_Student("Fei", 17, false);
        Console.Write(stu24.GetName());
        Console.Write(" is ");
        Console.WriteLine(stu24.GetAge());
        Console.WriteLine("UCAS complete: " + stu24.GetUCAS());
        stu24.ValidAge();

        P16_Student stu25 = new P16_Student("Bram", 12, false);
        stu25.ValidAge();

        Student stu1 = new Student("Bram", 12);
        stu1.ValidAge();
    }
}

Cmd Output:

Fei is 17
UCAS complete: false
Age Valid
Age Invalid
Age Valid
3