Wednesday, September 2, 2020

Abstract Classes and Members

  •  Abstract modifier used to indicate that a class or member is missing the implementation. 
  • The purpose of having a abstract class to provides a common definition of a base class that multiple derived classes can be shared.
  • We use abstract members when it doesn’t make sense to implement them in a base class. For example, the concept of drawing a shape is too abstract. We don’t know how to draw a shape. This needs to be implemented in the derived classes.
  •     public class Shape
        {
            public virtual void Draw()
            {
            }
        }
    
        public class Circle : Shape
        {
            public override void Draw()
            {
                Console.WriteLine("Drawing a circle");
            }
        }
    
    
  • In these situations, better approach is to use abstract modifier. In a derived class, we need to override all abstract members of the base class, otherwise that derived class is going to be abstract too.  
  •     public abstract class Shape
        {
            public abstract int Weight { get; set; }
            public abstract void Draw();
    		
            //Concrete Method
            public void Print()
            {
            }
    
        public class Circle : Shape
        {
            private int _weight;
            public override int Weight
            {
                get
                {
                    return _weight;
                }
    
                set
                {
                    Weight = _weight;
                }
            }
    
            public override void Draw()
            {
                Console.WriteLine("Drawing a circle");
            }
        }
    
  • When a class member is declared as abstract, that class needs to be declared as abstract as well. That means that class is not complete.
  • We can not define abstract variables and abstract class cannot be instantiated. 
  • In C#, "Stream" class is an abstract class and because it is too abstract. But FileStream is derived from System.IO.Stream and it is very specific. It allows to read and write data to file. 



No comments:

Post a Comment