Skip to content

Commit 87653eb

Browse files
committed
Adding example on inheritance.
1 parent 5edb778 commit 87653eb

4 files changed

Lines changed: 42 additions & 0 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class FMember : Person{
2+
public string Relationship;
3+
public FMember(string relationP, string nameP){
4+
// This implicitely calls
5+
// Person()
6+
// which exists to create first
7+
// a person object.
8+
Relationship = relationP;
9+
// the following
10+
// name = nameP;
11+
// gives
12+
// InheritanceAndAccessModifiers/FMember.cs(5,9): error CS0122: 'Person.name' is inaccessible due to its protection level
13+
// so we have to use the public method instead:
14+
SetName(nameP);
15+
16+
}
17+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
public class Person{
2+
private string name;
3+
public string GetName(){return name;}
4+
public Person(){}
5+
public void SetName(string nameP){name = nameP;}
6+
}
7+
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
class Program{
2+
public static void Main(){
3+
FMember test = new FMember("Cousin", "Samuel");
4+
}
5+
}

source/lectures/oop/inheritance.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,16 @@ We could then obtain a code as follows:
7474
Note that `SetNOW` inside the no-args constructor actually calls a `SetNOW` method inside `Bike`, but since there is no such method, it fallback to the `SetNOW` method from the `Vehicle` class.
7575
If there was a `SetNOW` method in both the `Bike` and the `Vehicle` method, we could not force access to the `Vehicle` method^[Actually, we could, if you read [this post](https://stackoverflow.com/a/32562464), but it is considered bad practice.].
7676
-->
77+
78+
## On Private and Public Methods and Attributes
79+
80+
The following example tries to make it clear that `private` attributes *cannot* be accessed from classes inheriting.
81+
82+
83+
```{download="./code/projects/InheritanceAndAccessModifiers.zip"}
84+
!include code/projects/InheritanceAndAccessModifiers/InheritanceAndAccessModifiers/Person.cs
85+
```
86+
87+
```{download="./code/projects/InheritanceAndAccessModifiers.zip"}
88+
!include code/projects/InheritanceAndAccessModifiers/InheritanceAndAccessModifiers/FMember.cs
89+
```

0 commit comments

Comments
 (0)