What is the difference between an interface and abstract class?

前端 未结 30 1791
情歌与酒
情歌与酒 2020-11-21 11:51

What exactly is the difference between an interface and abstract class?

30条回答
  •  野的像风
    2020-11-21 12:29

    Differences between abstract class and interface on behalf of real implementation.

    Interface: It is a keyword and it is used to define the template or blue print of an object and it forces all the sub classes would follow the same prototype,as for as implementation, all the sub classes are free to implement the functionality as per it's requirement.

    Some of other use cases where we should use interface.

    Communication between two external objects(Third party integration in our application) done through Interface here Interface works as Contract.

    Abstract Class: Abstract,it is a keyword and when we use this keyword before any class then it becomes abstract class.It is mainly used when we need to define the template as well as some default functionality of an object that is followed by all the sub classes and this way it removes the redundant code and one more use cases where we can use abstract class, such as we want no other classes can directly instantiate an object of the class, only derived classes can use the functionality.

    Example of Abstract Class:

     public abstract class DesireCar
      {
    
     //It is an abstract method that defines the prototype.
         public abstract void Color();
    
      // It is a default implementation of a Wheel method as all the desire cars have the same no. of wheels.   
     // and hence no need to define this in all the sub classes in this way it saves the code duplicasy     
    
      public void Wheel() {          
    
                   Console.WriteLine("Car has four wheel");
                    }
               }
    
    
        **Here is the sub classes:**
    
         public class DesireCar1 : DesireCar
            {
                public override void Color()
                {
                    Console.WriteLine("This is a red color Desire car");
                }
            }
    
            public class DesireCar2 : DesireCar
            {
                public override void Color()
                {
                    Console.WriteLine("This is a red white Desire car");
                }
            }
    

    Example Of Interface:

      public interface IShape
            {
              // Defines the prototype(template) 
                void Draw();
            }
    
    
      // All the sub classes follow the same template but implementation can be different.
    
        public class Circle : IShape
        {
            public void Draw()
            {
                Console.WriteLine("This is a Circle");
            }
        }
    
        public class Rectangle : IShape
        {
            public void Draw()
            {
                Console.WriteLine("This is a Rectangle");
            }
        }
    

提交回复
热议问题