A Sealed Class

Introduction

A sealed class is a class that cannot serve as a base class in inheritance. That is, you cannot derive a class from a sealed class.

Practical LearningPractical Learning: Introducing Static Classes

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the middle frame, click Empty Project (.NET Framework).
    Change the project Name to PayrollPreparation1
  4. Click OK
  5. On the main menu, click View -> Class View
  6. In the Class View, right-click PayrollPreparation1 -> Add -> Class...
  7. Type Calculations as the name of the class
  8. Click Add
    namespace PayrollPreparation1
    {
        public class Calculations
        {
        }
    }

Static Classes

As seen in previous lessons, a static class is a class marked with the static keyword and whose all members are static. When a class has been made static, no class can be derived from it. This means that when you create a static class, it becomes automatically sealed.

Practical LearningPractical Learning: Creating a Static Class

  1. To create a static class, change the Calculations class as follows:
    namespace PayrollPreparation1
    {
        public static class Calculations
        {
            public static double Add(double a, double b)
            {
                return a + b;
            }
    
            public static double Add5(double a, double b, double c, double d, double e)
            {
                return a + b + c + d + e;
            }
    
            public static double Subtract(double a, double b)
            {
                return a - b;
            }
    
            public static double Multiply(double a, double b)
            {
                return a * b;
            }
        }
    
        public class Operations : Calculations
        {
        }
    }
  2. In the Class View, right-click PayrollPreparation1 -> Add -> Class...
  3. In the middle list, make sure Class is selected.
    Type PayrollPreparation
  4. Press Enter
  5. To execute the project, on the main menu, click Debug -> Start Without Debugging
  6. You should receive an error. Read the text of the error in the message box
  7. Then click No and return to your programming environment
  8. Access the Calculations.cs file and delete the Operations class in the document:
    namespace PayrollPreparation1
    {
        public static class Calculations
        {
            public static double Add(double a, double b)
            {
                return a + b;
            }
    
            public static double Add5(double a, double b, double c, double d, double e)
            {
                return a + b + c + d + e;
            }
    
            public static double Subtract(double a, double b)
            {
                return a - b;
            }
    
            public static double Multiply(double a, double b)
            {
                return a * b;
            }
        }
    }

Sealing a Class

A regular class, that is, a non-static class, can be sealed so it would not act as a base class for another class. To let you seal a class, the C# language provides a keyword named sealed. Therefore, to seal a class, type the sealed keyword to the left of the class keyword.

If the class is marked with an access modifier, the sealed keyword can appear before or after the access modifier. Here are examples:

sealed public class TimeWorked
{

}

public sealed class WorkingTime
{

}

A class that is derived from another can also be sealed. Here is an example:

public abstract class Triangle
{
}

sealed public class Irregular : Triangle
{
}

Remember that once a class is sealed, it cannot serve as a parent of another class. As an alternative, the class can be used to create a property in another class that would use it as a pseudo-parent.

Practical LearningPractical Learning: Creating a Sealed Class

  1. In the Class View, right-click App_Code -> Add -> Class...
  2. Type Payroll as the name of the class
  3. Click Add
  4. In the Payroll.cs file, to create a sealed class, change the code as follows:
    namespace PayrollPreparation1
    {
        public sealed class Payroll
        {
            private double hSalary;
            private double timeSpecified;
    
            public Payroll(double salary, double time)
            {
                hSalary = salary;
                timeSpecified = time;
            }
    
            public double HourSalary
            {
                get { return hSalary; }
                set { hSalary = value; }
            }
    
            public double OvertimeSalary
            {
                get { return Calculations.Multiply(hSalary, 1.50); }
            }
    
            public double RegularTime
            {
                get
                {
                    if (timeSpecified <= 40.00)
                        return timeSpecified;
                    else
                        return 40.00;
                }
            }
    
            public double Overtime
            {
                get
                {
                    if (timeSpecified <= 40.00)
                        return 0.00;
                    else
                        return Calculations.Subtract(timeSpecified, 40.00);
                }
            }
    
            public double RegularPay
            {
                get
                {
                    return Calculations.Multiply(hSalary, RegularTime);
                }
            }
    
            public double OvertimePay
            {
                get
                {
                    return Calculations.Multiply(OvertimeSalary, Overtime);
                }
            }
    
            public double NetPay
            {
                get
                {
                    return Calculations.Add(RegularPay, OvertimePay);
                }
            }
        }
    
        public class TimeSheet : Payroll
        {
    
        }
    }
  5. To execute the application, on the main menu, click Debug -> Start Without Debugging
  6. You should receive an error. Read the text of the error in the message box, click No and return to your programming environment
  7. In the Payroll.cs file, delete the TimeSheet class in the document:
    namespace PayrollPreparation1
    {
        public sealed class Payroll
        {
            private double hSalary;
            private double timeSpecified;
    
            public Payroll(double salary, double time)
            {
                hSalary = salary;
                timeSpecified = time;
            }
    
            public double HourSalary
            {
                get { return hSalary; }
                set { hSalary = value; }
            }
    
            public double OvertimeSalary
            {
                get { return Calculations.Multiply(hSalary, 1.50); }
            }
    
            public double RegularTime
            {
                get
                {
                    if (timeSpecified <= 40.00)
                        return timeSpecified;
                    else
                        return 40.00;
                }
            }
    
            public double Overtime
            {
                get
                {
                    if (timeSpecified <= 40.00)
                        return 0.00;
                    else
                        return Calculations.Subtract(timeSpecified, 40.00);
                }
            }
    
            public double RegularPay
            {
                get
                {
                    return Calculations.Multiply(hSalary, RegularTime);
                }
            }
    
            public double OvertimePay => Calculations.Multiply(OvertimeSalary, Overtime);
            public double NetPay      => Calculations.Add(RegularPay, OvertimePay);
        }
    }
  8. Access the PayrollPreparation.cs file and change the document as follows:
    using static System.Console;
    using static System.Environment;
    
    namespace PayrollPreparation1
    {
        public class PayrollPreparation
        {
            internal static int Main()
            {
                Title = "Payroll Preparation";
                WriteLine("Payroll Preparation");
                WriteLine("---------------------------------");
                WriteLine("Enter the following values");
                Write("Hourly Salary: ");
                double salary = double.Parse(ReadLine());
                WriteLine("---------------------------------");
                Write("Entet the Time Worked for" + NewLine);
                Write("Monday:    ");
                double monday = double.Parse(ReadLine());
                Write("Tuesday:   ");
                double tuesday = double.Parse(ReadLine());
                Write("Wednesday: ");
                double wednesday = double.Parse(ReadLine());
                Write("Thursday:  ");
                double thursday = double.Parse(ReadLine());
                Write("Friday:    ");
                double friday = double.Parse(ReadLine());
    
                double totalTime = Calculations.Add5(monday, tuesday, wednesday, thursday, friday);
    
                Payroll preparation = new Payroll(salary, totalTime);
    
                Clear();
    
                Title = "Payroll Preparation";
    
                WriteLine("Payroll Preparation");
                WriteLine("------------------------------------------");
                Write("HourlySalary:     {0:F}", salary + NewLine);
                WriteLine("------------------------------------------");
                WriteLine("Time Worked");
                WriteLine("Monday Tuesday Wednesday Thursday Friday");
                WriteLine(" {0:F}   {1:F}     {2:F}    {3:F}    {4:F}",
                          monday, tuesday, wednesday, thursday, friday);
                WriteLine("==========================================");
                WriteLine("          Pay Summary");
                WriteLine("------------------------------------------");
                WriteLine("          Time   Pay");
                WriteLine("Regular:  {0:F}  {1:C}",
                          preparation.RegularTime, preparation.RegularPay);
                WriteLine("Overtime: {0:F}  {1:C}",
                          preparation.Overtime, preparation.OvertimePay);
                WriteLine("Regular:  {0:F}  {1:C}", totalTime, preparation.NetPay);
                WriteLine("==========================================");
    
                return 0;
            }
        }
    }
  9. To execute the application, press Ctrl + F5:
    ayroll Preparation
    --------------------------------
    nter the following values
    ourly Salary:
  10. For the Hourly Salary value, type a decimal number such as 17.85
  11. For the time worked for each day, type a decimal number between 0 and 16 in increment of 0.50. Here are examples:
    Payroll Preparation
    ---------------------------------
    Enter the following values
    Hourly Salary: 17,85
    ---------------------------------
    Entet the Time Worked for
    Monday:    8.00
    Tuesday:   9.50
    Wednesday: 10.50
    Thursday:  9.00
    Friday:    10.00
  12. Press Enter:
    Payroll Preparation
    ------------------------------------------
    HourlySalary:     1785
    ------------------------------------------
    Time Worked
    Monday Tuesday Wednesday Thursday Friday
     8.00   9.50     10.50    9.00    10.00
    ==========================================
              Pay Summary
    ------------------------------------------
              Time   Pay
    Regular:  40.00  $71,400.00
    Overtime: 7.00  $18,742.50
    Regular:  47.00  $90,142.50
    ==========================================
    Press any key to continue . . .
  13. Press Enter to close the DOS window and return to your programming environment

    Geometry - Rhombus

  14. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  15. In the middle list, click Empty Project (.NET Framework) and, in the Name text box, replace the name with Geometry12
  16. Click OK
  17. On the main menu, click View -> Class View
  18. In the Class View, right-click Geometry12 -> Add -> Class...
  19. Change the file Name to Quadrilateral
  20. Click Add
  21. Create a method in the class as follows:
    namespace Geometry12
    {
        public class Quadrilateral
        {
            public virtual double CalculateArea()
            {
                return 0.00;
            }
        }
    }
  22. In the Class View, right-click Geometry12 -> Add -> Class...
  23. Set the name of the class as Rhombus
  24. Click Add
  25. Fill the class as follows:
    using static System.Math;
    
    namespace Geometry12
    {
        public class Rhombus : Quadrilateral
        {
            public double Horizontal { get; set; }
            public double Vertical { get; set; }
    
            public Rhombus(double length, double high)
            {
                Vertical = high;
                Horizontal = length;
            }
        }
    }

Characteristics of a Sealed Class

A Sealed Method

If you use the sealed keyword on a class, the whole class becomes sealed, but you may not want the whole class to be sealed. Sometimes, you may want only some members to be sealed.

One of the charateristics of inheritance is that a derived class can provide a new behavior of a parent's method. This can be done by overriding a method of the parent. Sometimes when creating a non-sealed class, you may want to prevent the deriving class(es) from overriding a certain method. In this case, you can seal the method. A sealed method is one that doesn't allow deriving classes to override it.

If you create a new method in a derived class, that is, a method that does't exist in the parent class, you cannot seal it. This means that you can seal only a method that can be overridden. Therefore, before sealing a method, you must first create it in a class. You must mark that method as abstract or virtual.

Remember that, in a derived class, you must override every parent's abstract or virtual method. To seal a method, in the derived class, precede the return type by the sealed keyword. The sealed keyword can appear before or after override. Here are examples:

public abstract class RoundShape
{
    public virtual  double Radius { get; set; }
    public abstract double Diameter { get; }
}

public class Circle : RoundShape
{
    private double rad;

    public sealed override double Radius // sealed before override
    {
        get
        {
            return this.rad;
        }

        set
        {
            this.rad = value;
        }
    }

    public override sealed double Diameter // override before sealed = same thing
    {
        get
        {
            return this.rad * 2;
        }
    }
}

Practical LearningPractical Learning: Creating a Sealed Method

A Sealed Property

A property from a class A is said to be sealed if no class B deriving from class A is allowed to provide a new version of the property.

As seen for a method, before creating a sealed property, its class must be derived from another class. Here is an example of such as class created as abstract:

public abstract class RoundShape
{
    public virtual  double Radius { get; set; }
    public abstract double Diameter { get; }
}

Of course, you must derive a class from such a class. Before sealing a property, you must override it from the parent class. That is, you must mark the property in the derived class as override. To seal a property, type the sealed keyword close to the override keyword. The sealed keyword can appear before or after override.

Practical LearningPractical Learning: Creating a Sealed Property

  1. Acccess the Quadrilateral.cs file and create a virtual property in the Quadrilateral class as follows:
    namespace Geometry12
    {
        public class Quadrilateral
        {
            public virtual double CalculateArea()
            {
                return 0.00;
            }
    
            public virtual double Inradius { get; }
        }
    }
  2. Access the Rhombus.cs file
  3. In the Rhombus class, create a sealed property as follows:
    using static System.Math;
    
    namespace Geometry12
    {
        public class Rhombus : Quadrilateral
        {
            public double Horizontal { get; set; }
            public double Vertical { get; set; }
    
            public Rhombus(double length, double high)
            {
                Vertical = high;
                Horizontal = length;
            }
    
            public sealed override double CalculateArea()
            {
                return Horizontal * Vertical / 2.00;
            }
    
            public override sealed double Inradius
            {
                get
                {
                    if( (Horizontal == 0.00) || (Vertical == 0.00) )
                        return 0.00;
    
                    // http://mathworld.wolfram.com/Rhombus.html
                    return (Horizontal * Vertical) / (2.00 * Sqrt((Horizontal * Horizontal) + (Vertical * Vertical)));
                }
            }
        }
    }
  4. In the Class View, right-click Geometry12 -> Add -> Class...
  5. Type Geometry as the name of the file/class
  6. Click Add
  7. Change the document as follows:
    using static System.Console;
    using static System.Environment;
    
    namespace Geometry02
    {
        public class Geometry
        {
            internal static int Main()
            {
                double horiz = 0.00, vert = 0.00;
    
                Title = "Geometry - Rhombus";
                WriteLine("Geometry - Rhombus");
                WriteLine("---------------------------------");
                WriteLine("Enter the following values");
                Write("Horizontal: ");
                horiz = double.Parse(ReadLine());
                Write("Vertical:   ");
                vert = double.Parse(ReadLine());
    
                Rhombus quad = new Rhombus(horiz, vert);
    
                Clear();
                Title = "Geometry - Rhombus";
    
                WriteLine("Geometry - Rhombus");
                WriteLine("----------------------------------");
                Write("Horizontal:       {0}", quad.Horizontal + NewLine);
                Write("Vertical:         {0}", quad.Vertical + NewLine);
                Write("Inscribed Radius: {0}", quad.Inradius + NewLine);
                WriteLine("Area:             {0}", quad.CalculateArea());
                WriteLine("==================================");
    
                return 0;
            }
        }
    }
  8. To execute the project, press Ctrl + F5
    Geometry - Rhombus
    ---------------------------------
    Enter the following values
    Horizontal:
  9. Type some numbers in the Horizontal and the Vertical values. Here are examples:
    Geometry - Rhombus
    ---------------------------------
    Enter the following values
    Horizontal: 469.97
    Vertical:   317.58
  10. Press Enter:
    Geometry - Rhombus
    ----------------------------------
    Horizontal:       469.97
    Vertical:         317.58
    Inscribed Radius: 131.567395226468
    Area:             74626.5363
    ==================================
    Press any key to continue . . .
  11. Press Enter to close the DOS window and return to your programming environment

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2002-2019, FunctionX Next