05 Inheritance
05 Inheritance
Objectives
• Describe inheritance
– syntax
– meaning
– access
– construction
2
Inheritance basics
3
Motivation: repeated code
int id;
}
repeated code
class Employee
{
string name;
int age;
public void Birthday() { age++; }
double salary;
}
4
Inheritance syntax
5
Memory allocation
class Person
{
base string name;
fields int age;
... Student s = new Student();
}
6
Use of base services
class Person
{
base public void Birthday()
method {
age++;
}
Student s = new Student();
...
} s.Birthday();
7
Inheritance hierarchy
8
Single inheritance only
9
Meaning of inheritance
Person
Student Employee
10
Protected access
class Person
{
derived classes protected string name;
granted access protected int age;
...
}
11
Hiding inherited member
12
Calling base method
13
Construction and inheritance
construct
Student s = new Student("Ann", 23, 12345);
Student
14
Invoking base constructor
15
Selecting base constructor
16
Automatic invocation of base constructor
17
Base without default constructor
class Person
{
assume Person has public Person(string name, int age) { ... }
no default constructor ...
}
18
Summary
19