C# object oriented programming - classes and objects (abstract and sealed classes)

Posted by messer on Fri, 31 Dec 2021 03:45:27 +0100

Abstract classes and abstract methods

If a class is not associated with specific things, but only expresses an abstract concept and is only a base class of its derived classes, such a class is an abstract class. When declaring a method in an abstract class, if abstract is added, it is an abstract method
Overview and declaration of abstract classes the main differences between abstract classes and non abstract classes are as follows: (1) abstract classes cannot be instantiated directly.
(2) Abstract classes can contain abstract members, but not in non abstract classes.
(3) Abstract classes cannot be sealed.

Overview and declaration of abstract methods in abstract classes, the keyword absact can also be used to define abstract methods. All derived non abstract classes are required to overload the implementation of abstract methods. The reason for introducing abstract methods is that the abstract class itself is an abstract concept. Some methods do not need specific implementation, but are left for the overload implementation of derived classes. Note when declaring abstract methods:
(1) Abstract methods must be declared in abstract classes.
(2) virtual, static, and private modifiers cannot be used when declaring abstract methods.
(3) Abstract method declarations introduce a new method, but do not provide a concrete implementation.
(4) When deriving a non abstract class from an abstract class, you need to override the methods in all abstract classes in the non abstract class, provide specific implementation details, and use the override keyword when overriding abstract methods.

using System;
namespace Project16
{
    //Define base class Shape
    public abstract class Shape        //A graph that declares an abstract class
    {
        //protected: allows a derived class to access its base class members
        protected string Color;        //Represents the color of the drawing
        //The constructor helps the user initialize the object, that is, assign values to each attribute of the object in turn
        public Shape(string Color)     //Define a constructor with parameters to assign a value to the color of the graph
        {
            this.Color = Color;
        }
        public string GetColor()        //GetColor method to get graphic color
        {
            return Color;
        }
        public abstract double GetArea();   //Represents the area of the drawing
        //(1) Abstract methods must be declared in abstract classes.
        //(2) virtual, static, and private modifiers cannot be used when declaring abstract methods.
        //(3) Abstract method declarations introduce a new method, but do not provide a concrete implementation.
    }
    //Defines the Cirle class, derived from the Shape class
    public class Circle : Shape      //circular
    {
        //Function of private: only methods in the same class can access the variable
        private double Radius;      //Radius of circle
        //Through the base keyword, specify the base class constructor that should be called when creating a derived class instance.
        public Circle(string Color, double Radius) : base(Color)
        {
            this.Color = Color;
            this.Radius = Radius;
        }
        //When deriving a non abstract class from an abstract class, you need to use the override keyword to implement the methods in the non abstract class
        public override double GetArea()      //Override abstract methods
        {
            return System.Math.PI * Radius * Radius;
        }
    }
    //Derived class Rectangular, derived from Shape class
    public class Retangular : Shape       //rectangle
    {
        protected double Length, Width;   //Declaration length and width
        public Retangular(string Color, double Length, double Width) : base(Color)  //Constructor
        {
            this.Color = Color;
            this.Length = Length;
            this.Width = Width;
        }
        public override double GetArea()    //override method 
        {
            return (Length * Width);
        }
        public double PerimeterIs()   //Perimeter
        {
            return (2 * (Length + Width));
        }
    }
    //Derived class Square, derived from Retangular class
    public class Square : Retangular        //square
    {
        public Square(string Color, double Side) : base(Color, Side, Side) {; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Circle Cir = new Circle("yellow", 4.0);
            Console.WriteLine("The color of the circle is:{0},Its area is:{1}", Cir.GetColor(), Cir.GetArea());
            Retangular Rect = new Retangular("gules", 6.0, 8.0);
            Console.WriteLine("The color of the rectangle is:{0},Its area is:{1},Its circumference is:{2}",
                Rect.GetColor(), Rect.GetArea(), Rect.PerimeterIs());
            Square Squ = new Square("green", 5.0);
            Console.WriteLine("The color of the square is:{0},Its area is:{1},Its circumference is:{2}",
                Squ.GetColor(), Squ.GetArea(), Squ.PerimeterIs());
            Console.ReadKey();
        }
    }
}

[program analysis] this example demonstrates the use of abstract classes and methods. In the code, first, use the abstract keyword to declare the Shape class as an abstract class, in which the variable Color is defined to represent the Color; a constructor with parameters is defined to assign values to the variable Color; a GetColor method is defined to obtain the data of the variable Color; and an abstract class is declared The GetArea method is used to obtain the area of the drawing. Note here that abstract methods must be declared in abstract classes and cannot contain method bodies. Then, the Circle class and Rectangular class are derived from the Shape class, and the specific area can be calculated only by overriding the abstract method GetArea in both classes. Then, declare that the Square class inherits from the Rectangular class, and specify the base class constructor that should be called when creating a derived class instance through the base keyword.

The color of the circle is yellow and its area is 50.2654824574367
 The color of the rectangle is red, its area is 48 and its perimeter is 28
 The color of the square is green, its area is 25 and its circumference is 20

The difference between abstract classes and interfaces

Many C# beginners are easy to confuse abstract classes and interfaces when programming. This article will explain the difference between abstract classes and interfaces conceptually:

  1. abstract class
    A class with the abstract modifier is an abstract class. An abstract class is a special class, but it cannot be instantiated. You can create a variable whose type is an abstract class and let it point to an instance of a specific subclass;
  2. Interface
    Interfaces are reference types, similar to classes. There are three similarities between interfaces and abstract classes:
    (1) Cannot instantiate.
    (2) Contains an unimplemented method declaration.
    (3) Derived classes must implement unimplemented methods, abstract classes are abstract methods, and interfaces are all members.
  3. The grammatical difference between the two
    (1) Abstract classes can have constructors, but interfaces cannot have constructors.
    (2) There can be ordinary member variables in abstract classes, but there are no ordinary member variables in interfaces
    (3) Abstract classes can contain static methods, but interfaces cannot contain static methods
    (4) A class can implement multiple interfaces, but can only inherit one abstract class.
    (5) The specific methods implemented by abstract classes are virtual methods by default, but the interface methods in the classes that implement interfaces are non virtual methods by default. Of course, users can also declare them as virtual methods

Sealing class and sealing method

If all classes can be inherited, it is easy to lead to the abuse of inheritance, and then the hierarchy of classes becomes very complex, which makes it very difficult for developers to understand and use classes. In order to avoid abusing inheritance, the concept of sealed class is proposed in C#.

  1. Overview and declaration of sealing class
    Sealed classes can be used to limit extensibility. If a class is sealed, other classes cannot inherit from it; If a member is sealed, the derived class cannot override the implementation of the member.
  2. Overview and statement of sealing method
    Not every method can be declared as a sealed method. Sealed methods can only be used to implement the virtual methods of the base class and provide specific implementations. Therefore, when declaring a sealed method, the sealed modifier is always used together with the override modifier.
    Write a program, define a sealed method, and rewrite it.
using System;
namespace Project17
{
    public class MyClass1
    {
        public virtual void Write()
        {
            Console.WriteLine("This is an unsealed method");
        }
    }
    public class MyClass2:MyClass1
    {//After inheritance, you need to override the virtual method Write
        public sealed override void Write()
        {
            Console.WriteLine("This is a sealed method");
        }
    }
    public class MyClass3:MyClass2
    {
        //public override sealed void Write()
        //{
        //    Console.WriteLine("rewrite sealing method");
        //}
        //The inherited member 'MyClass2.Write()' is sealed and cannot be overridden 
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass2 myClass2 = new MyClass2();
            myClass2.Write();
            Console.ReadKey();
        }
    }
}

[program analysis] this example demonstrates the use of sealed methods. In the code, declare a class MyClass1, in which a virtual method method is declared. Then declare a class MyClass2, which inherits from MyClass1. In the sealed class MyClass2, seal and override the virtual method in MyClass1. If you declare a class MyClass3, inherit from MyClass2, and override the sealing method in MyClass2 Method, compiler is not allowed.

This is a sealed method
  1. Use of sealing classes and sealing methods
    Except that sealed classes cannot be inherited, the usage of sealed classes is roughly the same as that of unsealed classes, and sealed methods must be implemented by overriding virtual methods in the base class.
    Write a program to output the basic information of users through sealed classes and sealed methods.
using System;
namespace Project18
{
    public class MyClass1
    {
        public virtual void ShowInfo() //Virtual method to display information
        {
        }
    }
    public sealed class MyClass2 : MyClass1 //Sealed class, inheriting MyClass1
    {
        private string _id = "";
        private string _name = "";
        public string ID
        {
            get
            {
                return _id;
            }
            set
            {
                _id = value;
            }
        }
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }
        public sealed override void ShowInfo()
        {
            Console.WriteLine("I am{0},my ID yes{1}", Name, ID);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass2 myclass2 = new MyClass2();
            myclass2.ID = "BH0001";
            myclass2.Name = "Zhang San";
            myclass2.ShowInfo();
            Console.ReadKey();
        }
    }
}

[Program analysis] this example demonstrates the use of sealed classes and sealed methods. In the code, declare a class myclass1, in which a virtual method ShowInfo is declared to display information. Then declare a sealed class myclass2, which inherits from myclass1, and declare two public properties in myclass2 sealed class to represent user number and name respectively. Then seal and rewrite Myclass1 is the virtual method ShowInfo in the base class, and provides a specific implementation. Finally, instantiate an object of the myclass2 sealed class in the Main method of the Main Program class Program, and then use the object to access the public properties and sealed methods in the myclass2 sealed class. It should be noted here that when declaring a sealed method, it must be implemented by overriding the virtual method in the base class.

I'm Zhang San, mine ID yes BH0001

Topics: C# abstract class