1

mrahmedcomputing

KS3, GCSE, A-Level Computing Resources

Lesson 8. Inheritance


Lesson Objective

  • Understand Inheritance.

Lesson Notes

Inheritance

In C#, it is possible to inherit attributes and methods from one class to another. The "inheritance concept" is categorized into two groups:

In C#, to inherit from a class, use the : symbol..

In the following example, the P16_Student class (subclass) inherits the attributes and methods from the Student class (superclass)

main.c#

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

  public string Name
  {
    get { return name; }
    set { name = value; }
  }

  public int Age
  {
    get { return age; }
    set { age = value; }
  }
}

public class P16_Student : Student
{
}


public class Program
{
  public static void Main(string[] args)
  {
    P16_Student stu24 = new P16_Student();
    stu24.Name = "Fei";
    stu24.Age = 17;
    Console.Write(stu24.Name);
    Console.Write(" is ");
    Console.WriteLine(stu24.Age);
  }
}

Cmd Output:

Fei is 17

main.c#

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

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

    public string GetName() {
        return name;
    }

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

    public int GetAge() {
        return age;
    }

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

// New P16_Student Constructor has been created in this class. base is used to specify which parameters are inherited from the student superclass.

public class P16_Student : Student {
    private bool ucas;

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

    public bool GetUCAS() {
        return ucas;
    }

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

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

Cmd Output:

Fei is 17
UCAS complete: false