GCSE Link: None
Inheritance is a fundamental principle of OOP in which objects of a child class can use methods and attributes of a parent class.
Note that sometimes the child class is called a subclass or derived class, and the parent class can be called a super class or base class.
For example, a Car class could inherit from a Vehicle class, because they both
need similar methods and attributes. The Car class could then add extra
functionality that the generic Vehicle class does not have, but it could also
override some methods in the Vehicle class:
Polymorphism refers to the ability of different objects to respond to the same method call differently.
Example 1 shows an example of polymorphism.
Example 1
class Animal {
public virtual void Speak()
=> Console.WriteLine("");
}
class Cat: Animal {
public override void Speak()
=> Console.WriteLine("Meow");
}
class Dog: Animal {
public override void Speak()
=> Console.WriteLine("Woof");
}
Here, we have defined a generic Animal class, with a virtual method
(i.e. one that can be overridden) called Speak(). This is then
overridden in the Cat and Dog classes
which inherit from it. Calling the Speak() method on a
Cat object will output "Meow", and calling it
on a Dog object will output "Woof".
But we can also call the Speak() method on a generic
Animal object, which will output "". If we
don't want to allow generic Animal objects to be created, we can mark the
class as abstract, which means that it is simply a template for subclasses and cannot
itself be instantiated.
Abstract classes can also contain abstract methods which (unlike virtual methods) have no
implementation at all in the parent class, and must be overridden in the child class
(whereas virtual methods have the option to be overridden, but don't have to be).
Example 2 shows an abstract Animal class with an abstract Speak() method.
Example 2
abstract class Animal {
public abstract void Speak();
}
Modify the
Animal class to have a Name attribute.
How would the Cat and Dog classes need to be
modified to also have a Name variable?
abstract class Animal(string name) {
Because of inheritance, the
public string Name = name;
public abstract void Speak();
}
class Cat(string name):
Animal(name) {
public override void Speak()
=> Console.WriteLine("Meow");
}
class Dog(string name):
Animal(name) {
public override void Speak()
=> Console.WriteLine("Woof");
}
Cat and Dog
classes also have the Name attribute without many changes!