Fundamentals of Mixing Classes

Introduction

In previous lessons, when we needed a class, we created it, from scratch. If we needed a different class, we created a new one, even if the new class had only slight differences with an existing class.

Practical LearningPractical Learning: Introducing Classes

  1. Start Microsoft Visual Studio. In the Visual Studio 2019 dialog box, click Create a New Project (if Microsoft Visual Studio was already opened, on the main menu, click File -> New -> Project...)
  2. In the list of projects templates, click Empty Project (.NET Framework)
  3. Click Next
  4. Set the project Name to AltairRealtors1
  5. Click Create
  6. In the Solution Explorer, right-click AltairRealtors1 -> Add -> New Item...
  7. In the left list, under Visual C# Items, click Code and, in the middle list, click Code File
  8. Change the name to LivingResidence
  9. Click Add
  10. In the empty document, type type the following code:
    class Residence
    {
        public int Bedrooms { get; set; }
        public double Bathrooms { get; set; }
        public double MarketValue { get; set; }
        public string ConstructionStatus { get; set; }
    }

    Single-Family House

  11. On the main menu, click Project -> Add New Item...
  12. In the left list, under Visual C# Items, click Code and, in the middle list, click Code File
  13. Change the name to Description
  14. Click Add
  15. In the document, type the following code:
    class ResidenceDescription
    {
        static void Main()
        {
            Residence res = new Residence();
    
            res.Bedrooms = 1;
            res.Bathrooms = 1;
            res.ConstructionStatus = "Complete";
            res.MarketValue = 100_000;
    
            System.Console.WriteLine("==//== Altair Realtors ==//==");
            System.Console.WriteLine("--------------------------------");
            System.Console.Write("Number of Bedrooms:   ");
            System.Console.WriteLine(res.Bedrooms);
            System.Console.Write("Number of Bathrooms:  ");
            System.Console.WriteLine(res.Bathrooms);
            System.Console.Write("Construction Status:  ");
            System.Console.WriteLine(res.ConstructionStatus);
            System.Console.Write("Market Value:         $");
            System.Console.WriteLine(res.MarketValue);
            System.Console.WriteLine("================================");
        }   
    }
  16. To execute the project and see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    ==//== Altair Realtors ==//==
    --------------------------------
    Number of Bedrooms:   1
    Number of Bathrooms:  1
    Construction Status:  Complete
    Market Value:         $100000
    ================================
    Press any key to continue . . .
  17. Press any key to click the DOS window and return to your programming environment
  18. To create another class, on the main menu, click Project -> Add New Item...
  19. In the middle list, make sure Code File is selected.
    Change the name to House
  20. Click Add
  21. In the document, type the following code:
    class House
    {
        public int Bedrooms { get; set; }
        public double Bathrooms { get; set; }
        public double MarketValue { get; set; }
        public string ConstructionStatus { get; set; }
        public int Stories { get; set; }
        public int IndoorGarage { get; set; }
    }
  22. Click the Description.cs tab and change its document as follows:
    class ResidenceDescription
    {
        static void Main()
        {
            House res = new House();
    
            res.Bedrooms = 5;
            res.Bathrooms = 3.50;
            res.ConstructionStatus = "Ongoing";
            res.MarketValue = 615_425;
            res.IndoorGarage = 2;
            res.Stories = 3;
    
            System.Console.WriteLine("==//== Altair Realtors ==//==");
            System.Console.WriteLine("--------------------------------");
            System.Console.Write("Number of Bedrooms:   ");
            System.Console.WriteLine(res.Bedrooms);
            System.Console.Write("Number of Bathrooms:  ");
            System.Console.WriteLine(res.Bathrooms);
            System.Console.Write("Construction Status:  ");
            System.Console.WriteLine(res.ConstructionStatus);
            System.Console.Write("Market Value:         $");
            System.Console.WriteLine(res.MarketValue);
            System.Console.Write("Stories:              ");
            System.Console.WriteLine(res.Stories);
            System.Console.Write("Indoor Garage:        ");
            System.Console.WriteLine(res.IndoorGarage);
            System.Console.WriteLine("================================");
        }
        
    }
  23. To execute the project and see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    ==//== Altair Realtors ==//==
    --------------------------------
    Number of Bedrooms:   5
    Number of Bathrooms:  3.5
    Construction Status:  Ongoing
    Market Value:         $615425
    Stories:              3
    Indoor Garage:        2
    ================================
    Press any key to continue . . .
  24. Press any key to click the DOS window and return to your programming environment

An Object as Field or Property

If you already have a useful class but need just some extra functionality, instead of creating a different class from scratch, you can create a new class but you would add only the needed extra functionality. One way you can address this issue is that, in the new class, create a member (such as a field or a property) that uses the existing class as type.

In a class, you create a member whose data type is an existing class. There is nothing magical: Simply create the member like any other. Here is an example of a property whose type is a class:

class Processor
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Wattage { get; set; }
    public double Speed { get; set; } 
}

class Computer
{
    public string Category { get; set; }
    public string WirelessType { get; set; }
    public Processor Calculator { get; set; }
}

After creating the field or property whose type is a class, you can access the members of that type in a method of the class. To do this, type the name of the field or property, a period, and the desired member. Here is an example:

class Processor
{
    public double Speed { get; set; } 
}

class Computer
{
    public string Category { get; set; }
    public string WirelessType { get; set; }
    public Processor Calculator { get; set; }

    private void Describe()
    {
        Calculator.Speed = 5.33; // Ghz
    }
}

To access the members of the type outside the class, after declaring a variable of the class, type of the name of the variable, a period, the name of the field or property type, a period, and te desired member. Here is an example:

class Processor
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Wattage { get; set; }
    public double Speed { get; set; } 
}

class Computer
{
    public string Category { get; set; }
    public string WirelessType { get; set; }
    public Processor Calculator { get; set; }

    public void Describe()
    {
        Calculator = new Processor();

        Calculator.Speed = 5.33; // Ghz
    }
}

class Description
{
    static void Main()
    {
        Computer device = new Computer();

        device.Describe();
        device.Category = "Desktop";

        device.Calculator.Make  = "AMD";
        device.Calculator.Model = "Ryzen";
    }
}

Practical LearningPractical Learning: Introducing Inheritance

  1. Click the House.cs tab and change its code as follows:
    class House
    {
        public  int Stories { get; set; }
        public  int IndoorGarage { get; set; }
        public  Residence Living { get; set; }
    }
    
  2. Click the Description.cs tab and change its code as follows:
    class ResidenceDescription
    {
        static void Main()
        {
            House res = new House();
    
            res.IndoorGarage = 0;
            res.Stories = 2;
            res.Living.Bedrooms = 3;
            res.Living.Bathrooms = 2.50;
            res.Living.ConstructionStatus = "Needs Renovation";
            res.Living.MarketValue = 338_505;
    
            System.Console.WriteLine("==//== Altair Realtors ==//==");
            System.Console.WriteLine("--------------------------------");
            System.Console.Write("Number of Bedrooms:   ");
            System.Console.WriteLine(res.Living.Bedrooms);
            System.Console.Write("Number of Bathrooms:  ");
            System.Console.WriteLine(res.Living.Bathrooms);
            System.Console.Write("Construction Status:  ");
            System.Console.WriteLine(res.Living.ConstructionStatus);
            System.Console.Write("Market Value:         $");
            System.Console.WriteLine(res.Living.MarketValue);
            System.Console.Write("Stories:              ");
            System.Console.WriteLine(res.Stories);
            System.Console.Write("Indoor Garage:        ");
            System.Console.WriteLine(res.IndoorGarage);
            System.Console.WriteLine("================================");
        }
    }
  3. To execute the application, on the main menu, click Debug -> Start Without Debugging. This would produce:
    ==//== Altair Realtors ==//==
    --------------------------------
    Number of Bedrooms:   3
    Number of Bathrooms:  2.5
    Construction Status:  Needs Renovation
    Market Value:         $338505
    Stories:              2
    Indoor Garage:        0
    ================================
    Press any key to continue . . .
  4. Press Enter to close the window and return to your programming environment

Fundamentals of Inheritance

Introduction

Class inheritance is the ability to create a new class that gets its primary functionality from an existing class. Before using inheritance, you must have a class. You can create it like any of the classes we have created so far.

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 (such as public). 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 first create a class. This means that you must use a class that exists aleady. Here is an example of starting a class inheritance:

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:

class Circle
{
}

public class Cylinder : Circle
{

}

After deriving a class, it becomes available and you can use it.

Practical LearningPractical Learning: Deriving From a Class

Accessing the Members of a Parent Class

When creating a class that can be used as a parent of other classes, if you don' want a member to be accessd from outside the class, mark that member with the private keyword. If you want to access a member from the child classes, makr that member as public.

To access a member of a parent class from a child class, if the parent member is public, simply use its name. Here an example:

class House : Residence
{
    public  int Stories { get; set; }
    public  int IndoorGarage { get; set; }

    void Initialize()
    {
        Bedrooms = 3;
    }
}

Before accessing a member of the parent class from outside the child class, first declare a variable for the child class. Type type the name of the variable, a period, and the desired memober from the parent class.

Practical LearningPractical Learning: Accessing the Members of a Parent Class

  1. Click the Description.cs tab and change its code as follows:
    class ResidenceDescription
    {
        static void Main()
        {
            House res = new House();
    
            res.IndoorGarage = 1;
            res.Stories = 2;
            res.Bedrooms = 4;
            res.Bathrooms = 3.50;
            res.ConstructionStatus = "Complete";
            res.MarketValue = 427_688;
    
            System.Console.WriteLine("==//== Altair Realtors ==//==");
            System.Console.WriteLine("--------------------------------");
            System.Console.Write("Number of Bedrooms:   ");
            System.Console.WriteLine(res.Bedrooms);
            System.Console.Write("Number of Bathrooms:  ");
            System.Console.WriteLine(res.Bathrooms);
            System.Console.Write("Construction Status:  ");
            System.Console.WriteLine(res.ConstructionStatus);
            System.Console.Write("Market Value:         $");
            System.Console.WriteLine(res.MarketValue);
            System.Console.Write("Stories:              ");
            System.Console.WriteLine(res.Stories);
            System.Console.Write("Indoor Garage:        ");
            System.Console.WriteLine(res.IndoorGarage);
            System.Console.WriteLine("================================");
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging. This would produce:
    ==//== Altair Realtors ==//==
    --------------------------------
    Number of Bedrooms:   4
    Number of Bathrooms:  3.5
    Construction Status:  Complete
    Market Value:         $427688
    Stories:              2
    Indoor Garage:        1
    ================================
    Press any key to continue . . .
  3. Press Enter to close the window and return to your programming environment

Creating a Grand-Child

You can create a class that adds some functionality to a class that itself is derived from another. One approach is to proceed as we saw in our introduction to mixing classes: In the new class, create a member that is of the child class type. Here is an example:

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Student : Person
{
    public int StudentNumber { get; set; }
    public string Grade { get; set; }
}

class ReportCard
{
    public string SchoolYear { get; set; }
    public Student Pupil { get; set; }
}

Otherwise, you can create a class that is derived from a class that itself is based on another class. Here is an example:

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public string DateOfBirth { get; set; }
}

class Adult : Person
{
    public string HighestEducationLevel { get; set; }
    public string MaritalStatus { get; set; }
}

class Employee : Adult
{
    public int EmployeeNumber { get; set; }
    public double HourlySalary { get; set; }
    public string DateHired { get; set; }
}

In the same way, you can create a class that is based on class that is itself is based on a class that is derived from another class that in turn descends from another class, and so on.

Introductory Characteristics of Inheritance

A Public Class

Sometimes, you will work on a solution that includes many projects. Sometimes too, you will create classes that you want to use in different projects. To make sure that a class is made for that type of exchange, create it as a public class. To do that, mark the class with the public keyword, which is written on the left side of the class keyword. Here is an example:

public class Book
{
    
}

If you are creating a class that will be used in one project, the public keyword in not required. Still, in that case, you can apply the public keyword if you want (it doesn't have any negative impact; in fact, it may be good to simply mark all your classes as public).

Remember that you can create many classes in the same document. In that case, you can mark some classes with the public keyword and omit it for some other classes. Here is an example:

class Schaool
{

}

public class Country
{

}

class PoliticalParty
{

}

You can mark a partial class with an access level. In this case, you can write the public keyword to the left of the partial keyword. Here is an example:

public partial class Person
{
    
}

Inheritance with a Public Class

If you create a class that is based on another class, if you decide to make the child class public, the compiler will check the access level of the parent class. If the parent is not made public, you would receive an error. The suggestion is to either make the parent class public or not apply the access level to the classes. Here is an example:

public class Schaool
{

}

public class Country
{

}

Partial Classes and Inheritance

If you create a class as a partial one, you can create another class based on it. Here is an example:

partial class Road
{
    
}

class Highway : Road
{
    
}

The child class doesn't have to be partial, although it can be. You can create a partial class that is derived from a non-partial class. Here is an example:

class EletronicMemory
{
    public int Capacity { get; set; }
}

partial class HardDrive : EletronicMemory
{
    public string Make { get; set; }
    public string Model { get; set; }
}

You can also create a partial class that is derived from a partial class. Here is an example:

partial class Road
{

}

partial class Interstate : Road
{

}

Remember that you can mark a partial class with an access level. This is also valid in inheritance. Here are examples:

public partial class Road
{

}

public partial class Interstate : Road
{

}

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2021, C# Key Next