Abstract classes vs. interfaces vs. mixins

后端 未结 7 1408
难免孤独
难免孤独 2021-01-29 20:10

Could someone please explain to me the differences between abstract classes, interfaces, and mixins? I\'ve used each before in

7条回答
  •  孤独总比滥情好
    2021-01-29 20:19

    An abstract class is a class that not all of its members are implemented ,they are left for the inheritors to be implemented.It forces its inheritors to implement its abstract members. Abstract classes can't be instantiated and thus their constructors shouldn't be public.]

    Here's an example in C#:

        public abstract class Employee
        {
            protected Employee(){} 
            public abstract double CalculateSalary(WorkingInfo workingInfo);//no implementation each type of employee should define its salary calculation method.
        }
    
       public class PartTimeEmployee:Employee
      {
        private double _workingRate;
        public Employee(double workingRate)
        {
         _workingRate=workingRate;
        }
        public override double CalculateSalary(WorkingInfo workingInfo)
        {
          return workingInfo.Hours*_workingRate;
        }
    

    }

    An interface is a contract to be implemented by a class.It just declare the signature of the members of an implementing class and it has no implementation itself.We usually use interfaces to implement polymorphism,and to decouple dependent classes.

    Here's an example in C#:

    public interface IShape
    {
    int X{get;}
    int Y{get;}
    void Draw();
    }
    
    public class Circle:IShape
    {
    public int X{get;set;}
    public int Y{get;set;}
    
    public void Draw()
    {
    //Draw a circle
    }
    }
    
    public class Rectangle:IShape
    {
    public int X{get;set;}
    public int Y{get;set;}
    
    public void Draw()
    {
    //Draw a rectangle
    }
    }
    

提交回复
热议问题