Fundamentals of Inheritance

Introduction

We already know that a property of a class can be of a class-type. This gives you the benefits of an existing object that you can just add to a new class instead of starting everything from scratch.

Practical Learning: Introducing Inheritance

1. Save the following picture somewhere on your computer:

2. Start Microsoft Visual Studio
3. To create a new application, on the main menu, click File -> New -> Project...
4. In the middle list, click ASP.NET Application (.NET Framework) and set the project Name to Geometry07
5. Click OK
6. In the New ASP.NET Web Application dialog box, make sure Empty is active and click OK
7. In the Solution Explorer, right-click the name of the project -> Add -> New Folder
8. Type images and press Enter
9. In a file utility such as Windows Explorer or File Explorer, right-click the cylinder.png file you had save and click Copy. Right-click the images folder of this project and click Paste
10. In the Solution Explorer, right-click Geometry07 -> Add -> New Item...
11. In the left list, click Code
12. In the middle list, click Code File
13. Change the name to Rectangle
15. Change the code as follows:
```public class Rectangle
{
public Rectangle()
{
Width = 0.00;
Height = 0.00;
}

public Rectangle(double wide, double high)
{
Width = wide;
Height = high;
}

public double Width { get; set; }
public double Height { get; set; }
public double Area { get { return Width * Height; } }
public double Perimeter { get { return (Width + Height) * 2; } }
}```
17. In the left list, click Code
18. In the middle list, click Code File
19. Change the name to Circle
21. Change the code as follows:
```public class Circle
{
public Circle()
{
}

{
}

public double Radius { get; set; }
public double Area { get { return Radius * Radius * Math.PI; } }
public double Diameter { get { return Radius * 2; } }
public double Circumferemce
{
get { return Diameter * Math.PI; }
}
}```
23. In the left list, click Code
24. In the middle list, click Code File
25. Change the name to Cylinder
27. Change the code as follows:
```public class Cylinder
{
{
Lateral = new Rectangle(Base.Circumferemce, height);
}

public Circle Base { get; set; }
public Rectangle Lateral { get; set; }

public double BaseArea { get { return Base.Area; } }
public double LateralArea { get { return Lateral.Area; } }
public double Volume { get { return BaseArea * Lateral.Height; } }
}```
29. In the left list, expand Web, and click Razor
30. In the middle list, click Web Page (Razor v3)
31. Change the name as Index
33. Type the code as follows:
```<!DOCTYPE html>
<html>
<style>
.container {
margin: auto;
width: 600px;
}

.txtSize {
width: 60px;
}
</style>
<title>Geometry - Cylinder</title>
<body>
@{
double height = 0.00;
Cylinder cyl = new Cylinder();

if (IsPost)
{
height = Convert.ToDouble(Request["txtHeight"]);

}
}

<div class="container">
<h3 style="text-align: center">Geometry - Cylinder</h3>

<form name="frmGeometry" method="post">
<table style="width: 600px">
<tr>
<td rowspan="7" style="text-align: center"><img src="~/images/cylinder.png" alt="Geomtry - Cylinder" width="261" height="281" /></td>
</tr>
<tr>
<td>Height:</td>
<td>
<input name="txtHeight" value="@height" class="txtSize" />
<input type="submit" name="btnCalculate" value="Calculate" />
</td>
</tr>
<tr>
<td>Diameter:</td>
<td><input name="txtDiameter" value="@cyl.Base.Diameter.ToString()" /></td>
</tr>
<tr>
<td>Base Conference:</td>
<td><input name="txtBaseConference" value=@cyl.Base.Circumferemce.ToString() /></td>
</tr>
<tr>
<td>Base Area:</td>
<td><input name="txtBaseArea" value=@cyl.Base.Area /></td>
</tr>
<tr>
<td>Lateral Area:</td>
<td><input name="txtLateralArea" value="@cyl.Lateral.Area" /></td>
</tr>
<tr>
<td>Volume:</td>
<td><input name="txtVolume" value="@cyl.Volume.ToString()" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>```

35. In the Radius text box, type a decimal number such as 28.86
36. In the Height text box, type a decimal number such as 49.73

37. Click the button:

39. To start a new application, on the main menu of Microsoft Visual Studio, click File -> New -> Project...
40. In the middle list, click ASP.NET Application (.NET Framework) and set the project Name to Geometry08
41. Click OK
42. In the New ASP.NET Web Application dialog box, click Empty and click OK
43. In the Solution Explorer, right-click the name of the project -> Add -> New Folder
44. Type Images and press Enter
45. In a file utility such as Windows Explorer or File Explorer, right-click the cylinder.png file you had save and click Copy. Right-click the images folder of this project and click Paste
46. In the Solution Explorer, right-click Geometry08 -> Add -> New Item...
47. In the left list, click Code
48. In the middle list, click Code File
49. Change the Name to Circle
51. Change the document as follows:
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Circle
{

public Circle()
{
}

{
}

{
get
{
}

set
{
}
}

public double Area { get { return radius * radius * Math.PI; } }
public double Diameter { get { return radius * 2; } }
public double Circumferemce
{
get { return Diameter * Math.PI; }
}
}```
52. In the Solution Explorer, right-click the name of the project -> Add -> New Item...
53. In the left list, click Code
54. In the middle list, click Code File
55. Change the Name to Cylinder
57. Change the document as follows:
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Cylinder : Circle
{
public double Height { get; set; }

public Cylinder(double baseRadius = 0.00, double height = 0.00)
{
Height = height;
}

public double LateralArea
{
get
{
return Circumferemce * Height;
}
}

public double Volume
{
get
{
return Area * Height;
}
}
}```

Class Derivation

Instead of creating a member of a class so that the member is of a class type, you can create a class that gets its foundation from another class. Class inheritance consists of creating a class that gets its foundation from another class. To create inheritance, you must have a class that provides the fundamental definition or behavior that another class would need.

Creating a class that is based on another class is also referred to as deriving a class from another. The first class serves as parent or base. The class that is based on another class is also referred to as child or derived. To create a class based on another, use the following formula:

```options class child-class : parent-class
{
Body of the new class
}```

Among the available options, you can start with an access level (public or internal). This is followed by the class keyword and a name for the new class. To indicate that the new class is based on another class, type a colon followed by the name of the base class. For a parent class, you can use one of the .NET Framework built-in classes (but not all classes can be used in inheritance) or you can first create your own class. This means that you must use a class that exists aleady. Here is an example of starting a class inheritance:

```public class Circle
{
}

class Cylinder : Circle
{

}```

If you want to be able to access the class from other languages, you can precede its name with the public keyword. Here is an example:

```public class Circle
{
}

public class Cylinder : Circle
{

}```

After deriving a class, it becomes available and you can use it just as you would any other class. Of course, you must first declare a variable for it.

Practical Learning: Deriving From a Class

• Change the Cylinder class as follows:
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Cylinder : Circle
{
. . . No Change
}```

A Review of Access Levels

When creating a class and when dealing with inheritance, you can control what members can be accessed from outside the class and/or from only inherited members.

As introduced and used in previous lessons, a member of a class is referred to as private if it can be accessed only from within the class. To create a private member variable, type the private keyword to its left. A member variable of a class is internal if it can be accessed by any class of the same project. To create such a member variable, precede it with the internal keyword. A member variable is referred to as public if it can be accessed by the classes of the same file. To create a public member variable of a class, precede it with the public keyword.

The Protected Members of a Class

Besides being made private, a member of a class can be protected to restrict its access. As seen for a private member, a protected member can be accessed by members of the same class. To let you protect a member of a class from non-deriving classes, the C# language provides a keyword named protected. Therefore, to indicate that a member is protected, set its access type to the protected keyword.

The main difference between a private and a protected member is that a protected member can be accessed by the members of its class but also the members of (a) derived class(es). Outside of those two environments, the access to a protected member would produce an error. Both the properties and the methods of a class can be protected.

If you create a member of a class and mark it as protected, the classes derived from its parent class, created in the current project or outside the current project, can access it. If you want the member to be accessed only by derived classes implemented in the same project but not the derived classes outside of the current project, mark the member as protected internal. Here are examples:

```public class Person
{
private string _name;
private string _gdr;

public Person(string name = "Not Available",
string gender = "Unknown")
{
_name = name;
_gdr  = gender;
}

protected internal string FullName
{
get { return _name; }
set { _name = value; }
}

protected internal string Gender
{
get { return _gdr; }
set { _gdr = value; }
}
}```

Practical Learning: Protecting a Member of a Class

1. Access the Circle.cs file and change its class as follows:
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Circle
{

public Circle()
{
}

{
}

{
get
{
}

set
{
}
}

public double Area { get { return radius * radius * Math.PI; } }
public double Diameter { get { return radius * 2; } }
public double Circumferemce
{
get { return Diameter * Math.PI; }
}
}```
2. Access the Cylinder.cs file and change its class as follows:
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Cylinder : Circle
{
public double Height { get; set; }

public Cylinder(double baseRadius = 0.00, double height = 0.00)
{
Height = height;
}

public double LateralArea
{
get
{
return Circumferemce * Height;
}
}

public double Volume
{
get
{
return Area * Height;
}
}
}```
3. In the Solution Explorer, right-click the name of the project -> Add -> New Item...
4. In the left list, expand Web, and click Razor
5. In the middle list, click Web Page (Razor v3)
6. Change the Name to Index
8. Change the code as follows:
```<!DOCTYPE html>
<html>
<title>Geometry - Cylinder</title>
<style>
.container {
margin: auto;
width: 600px;
}

.txtSize {
width: 60px;
}
</style>
<body>
@{
double height = 0.00;
Cylinder cyl = new Cylinder();

if (IsPost)
{
height = Convert.ToDouble(Request["txtHeight"]);

}
}

<div class="container">
<h3 style="text-align: center">Geometry - Cylinder</h3>

<form name="frmGeometry" method="post">
<table style="width: 600px">
<tr>
<td rowspan="7" style="text-align: center"><img src="~/images/cylinder.png" alt="Geomtry - Cylinder" width="261" height="281" /></td>
</tr>
<tr>
<td>Height:</td>
<td>
<input name="txtHeight" value="@height" class="txtSize" />
<input type="submit" name="btnCalculate" value="Calculate" />
</td>
</tr>
<tr>
<td>Diameter:</td>
<td><input name="txtDiameter" value="@cyl.Diameter.ToString()" /></td>
</tr>
<tr>
<td>Base Conference:</td>
<td><input name="txtBaseConference" value=@cyl.Circumferemce.ToString() /></td>
</tr>
<tr>
<td>Base Area:</td>
<td><input name="txtBaseArea" value=@cyl.Area /></td>
</tr>
<tr>
<td>Lateral Area:</td>
<td><input name="txtLateralArea" value="@cyl.LateralArea" /></td>
</tr>
<tr>
<td>Volume:</td>
<td><input name="txtVolume" value="@cyl.Volume.ToString()" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>```

10. In the Radius text box, type a decimal number such as 63.97
11. In the Height text box, type a decimal number such as 117.08

12. Click the button:

Characteristics of Inheritance

Partial Class Implementation

In C#, you can create a class (the same class) in different files. This means that you can start a class in one file and continue it in another file or in other files. This is referred to as partial implementation.

As we have seen so far, in C#, you cannot simply and only declare a method in a file for a forward (later) implementation. In C#, to create a class in various files, start the class in one file but precede the class keyword with partial. Here is an example of a file named first.cs that contains some (2) private fields and some (2) properties:

 Source File: CylinderPart1.cs ```public partial class Cylinder { private double rad; private double hgt; public Cylinder(double radius = 0, double height = 0) { this.rad = radius; this.hgt = height; } public double Radius { get { return rad; } set { rad = value; } } public double Height { get { return hgt; } set { hgt = value; } } }```

After creating the class in one file, you can use it like any of the classes as we have done so far. Here is an example:

 Source File: Index.cshtml ``` Coffee Mug Manufacturer @{ Cylinder cup = new Cylinder(36.12, 18.84); }

Cup Characteristics

Height: @cup.Height

```

If you had created a partial class, or you got a partial class from somebody (not as part of a DLL nor from another type of library), and you find out that the class is not complete, you can then complement it. There are rules you must follows:

• The partial class must have been marked as partial in its original creation, as we did above
• You must use the same name for the class
• You must precede the class keyword with partial

. One of the advantages of partial implementation is that you don't have to get back to the first or previous file to modify it in order to complement the class. You can simply start another file and continue the class in it. Here is an example:

 Source File: CylinderPart2.cs ```public partial class Cylinder { class public Cylinder() { this.rad = 0.00; this.hgt = 0.00; } public double Volume() { return rad * rad * hgt * Math.PI; } }```
 Source File: Index.cshtml ``` Coffee Mug Manufacturer @{ Cylinder cup = new Cylinder(36.12, 18.84); }

Cup Characteristics

Height: @cup.Height

Volume: @cup.Volume()

```

Once a partial class has been created, you can create another class based on it. The child class doesn't have to be partial, although it can be.

Practical Learning: Introducing Partial Class Implementation

1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
2. In the middle list, click ASP.NET Application (.NET Framework) and set the project Name to PayrollPreparation10
3. Click OK
4. In the New ASP.NET Web Application dialog box, click Empty and press Enter
6. Change the name to Overtimes
7. Press Enter
8. Change the code as follows:
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PayrollPreparation10
{
public partial class TimeSheet
{
public double Monday { get; set; }
public double Tuesday { get; set; }
public double Wednesday { get; set; }
public double Thursday { get; set; }
public double Friday { get; set; }

public TimeSheet()
{
Monday = 0.00;
Tuesday = 0.00;
Wednesday = 0.00;
Thursday = 0.00;
Friday = 0.00;
}

public TimeSheet(double mon, double tue,
double wed, double thu, double fri)
{
Monday = mon;
Tuesday = tue;
Wednesday = wed;
Thursday = thu;
Friday = fri;
}

public double MondayOvertime    => (Monday    <= 8.00) ? 0.00 : (Monday    - 8.00);
public double TuesdayOvertime   => (Tuesday   <= 8.00) ? 0.00 : (Tuesday   - 8.00);
public double WednesdayOvertime => (Wednesday <= 8.00) ? 0.00 : (Wednesday - 8.00);
public double ThursdayOvertime  => (Thursday  <= 8.00) ? 0.00 : (Thursday  - 8.00);
public double FridayOvertime    => (Friday    <= 8.00) ? 0.00 : (Friday    - 8.00);
}
}```
9. In the Solution Explorer, right-click the name of the project -> Add -> Class...
10. Change the name to RegularTimes
12. Type code as follows:
```using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PayrollPreparation10
{
public partial class TimeSheet
{
public double MondayRegularTime    => (Monday    <= 8.00) ? Monday    : 8.00;
public double TuesdayRegularTime   => (Tuesday   <= 8.00) ? Tuesday   : 8.00;
public double WednesdayRegularTime => (Wednesday <= 8.00) ? Wednesday : 8.00;
public double ThursdayRegularTime  => (Thursday  <= 8.00) ? Thursday  : 8.00;
public double FridayRegularTime    => (Friday    <= 8.00) ? Friday    : 8.00;
}
}```
13. In the Solution Explorer, right-click the name of the project -> Add -> New Item...
14. In the left list, expand Web and click Razor
15. In the middle list, click Web Page (Razor v3)
16. Change the name to Index
18. Change the document as follows:
```<!DOCTYPE html>
<html>
<title>Fun Department Store - Payroll Preparation</title>
<style>
.container {
margin: auto;
width: 575px;
}
</style>
<body>
<div class="container">
<h2 style="text-align: center">Fun Department Store</h2>
<h3 style="text-align: center">Payroll Preparation</h3>

@{
string strMondayRegularTime = "0.00", strMondayOvertime = "0.00";
string strTuesdayRegularTime = "0.00", strTuesdayOvertime = "0.00";
string strFridayRegularTime = "0.00", strFridayOvertime = "0.00";
string strWednesdayRegularTime = "0.00", strWednesdayOvertime = "0.00";
string strThursdayRegularTime = "0.00", strThursdayOvertime = "0.00";

PayrollPreparation10.TimeSheet ts = new PayrollPreparation10.TimeSheet();

if (IsPost)
{
double mon = Convert.ToDouble(Request["txtMonday"]);
double tue = Convert.ToDouble(Request["txtTuesday"]);
double wed = Convert.ToDouble(Request["txtWednesday"]);
double thu = Convert.ToDouble(Request["txtThursday"]);
double fri = Convert.ToDouble(Request["txtFriday"]);

ts = new PayrollPreparation10.TimeSheet(mon, tue, wed, thu, fri);

strMondayRegularTime = ts.MondayRegularTime.ToString("F");
strTuesdayRegularTime = ts.TuesdayRegularTime.ToString("F");
strWednesdayRegularTime = ts.WednesdayRegularTime.ToString("F");
strThursdayRegularTime = ts.ThursdayRegularTime.ToString("F");
strFridayRegularTime = ts.FridayRegularTime.ToString("F");

strMondayOvertime = ts.MondayOvertime.ToString("F");
strTuesdayOvertime = ts.TuesdayOvertime.ToString("F");
strWednesdayOvertime = ts.WednesdayOvertime.ToString("F");
strThursdayOvertime = ts.ThursdayOvertime.ToString("F");
strFridayOvertime = ts.FridayOvertime.ToString("F");
}
}

<form name="frmPayrollPreparation" method="post">
<table>
<tr>
<td>&nbsp;</td>
<td>Monday</td>
<td>Tuesday</td>
<td>Wednesday</td>
<td>Thursday</td>
<td>Friday</td>
</tr>
<tr>
<td style="width: 110px">Time Workd:</td>
<td><input type="text" name="txtMonday" style="width: 80px" value="@ts.Monday" /></td>
<td><input type="text" name="txtTuesday" style="width: 80px" value="@ts.Tuesday" /></td>
<td><input type="text" name="txtWednesday" style="width: 80px" value="@ts.Wednesday" /></td>
<td><input type="text" name="txtThursday" style="width: 80px" value="@ts.Thursday" /></td>
<td><input type="text" name="txtFriday" style="width: 80px" value="@ts.Friday" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td colspan="5" style="text-align: center; height: 32px;"><input type="submit" name="btnCalculate" style="width: 400px" value="Calculate" /></td>
</tr>
<tr>
<td>Regular Times:</td>
<td><input type="text" name="txtMondayRegularTime" style="width: 80px" value="@strMondayRegularTime" /></td>
<td><input type="text" name="txtTuesdayRegularTime" style="width: 80px" value="@strTuesdayRegularTime" /></td>
<td><input type="text" name="txtWednesdayRegularTime" style="width: 80px" value="@strWednesdayRegularTime" /></td>
<td><input type="text" name="txtThursdayRegularTime" style="width: 80px" value="@strThursdayRegularTime" /></td>
<td><input type="text" name="txtFridayRegularTime" style="width: 80px" value="@strFridayRegularTime" /></td>
</tr>
<tr>
<td>Overtimes:</td>
<td><input type="text" name="txtMondayOvertime" style="width: 80px" value="@strMondayOvertime" /></td>
<td><input type="text" name="txtTuesdayOvertime" style="width: 80px" value="@strTuesdayOvertime" /></td>
<td><input type="text" name="txtWednesdayOvertime" style="width: 80px" value="@strWednesdayOvertime" /></td>
<td><input type="text" name="txtThursdayOvertime" style="width: 80px" value="@strThursdayOvertime" /></td>
<td><input type="text" name="txtFridayOvertime" style="width: 80px" value="@strFridayOvertime" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>```
19. To execute the project, press Ctrl + F5

20. In each day's text box, type a decimal number between 0 and 16 but divisible by 0.50. Here are examples:

21. Click the Calculate button:

Namespaces and Inheritance

Imagine you had created a class named Element in a namespace named Chemistry as follows:

```namespace Chemistry
{
public class Element
{
}
}```

To derive a class from a class that belongs to a namespace, type the name of the namespace, followed by the period operator ".", and followed by the name of the base namespace. Here is an example:

```namespace Chemistry
{
public class Element
{
}
}

public class Isotope : Chemistry.Element
{
public int NeutronNumber { get; set; }
}```

If you need to call the class that was defined in a different namespace, you can qualify its name with the period operator. Here is an example:

```namespace Chemistry
{
public class Element
{
}
}

public class Isotope : Chemistry.Element
{
public int NeutronNumber { get; set; }
}

public class Exercise
{
public void Create()
{
Chemistry.Element h = new Chemistry.Element();
}
}```

Alternatively, to use the contents of a namespace, prior to calling a member of that namespace, you can type the using keyword followed by the name of the namespace. Here is an example:

```using Chemistry;

public class Isotope : Element
{
public int NeutronNumber { get; set; }
}

public class Exercise
{
public void Create()
{
Element h = new Element();
}
}```

Consider the following class named Matter and that is created in a nested namespace:

```namespace Chemistry
{
public class Element
{
}

namespace Atoms
{
namespace Nucleons
{
public class Proton
{
public string Symbol { get; set; }
}

public class Neutron
{
}
}

public class Matter
{
public double Mass { get; set; }
}
}
}```

If you want to create a class that is based on a class in a nested namespace, you can qualify its name. Here is an example:

```public class Atom : Chemistry.Atoms.Matter
{
public Chemistry.Element Element { get; set; }
public Nucleus Nucleus { get; set; }
}```

Practical Learning: Ending the Lesson