[转] Difference between Abstract classes and Interfaces

Abstract Class versus Interface

引自:http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

 

By Rahman Mahmoodi | 7 Jan 2008
Abstract class versus Interface: Usage and Implementation.

Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:

Feature

Interface

Abstract class

Multiple inheritance

A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access ModfiersAn interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed

Requires more time to find the actual method in the corresponding classes.

Fast

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and ConstantsNo fields can be defined in interfacesAn abstract class can have fields and constrants defined

Using the Code

Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.

I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.

In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.

Abstract Class Employee
Collapse | Copy Code
 System;

 AbstractsANDInterfaces
{
    


    

    

    
       Employee
    {
        


        

          id;
          lname;
          fname;

        


           ID
        {
            ;
            ;
        }

           FirstName
        {
            ;
            ;
        }
        
           LastName
        {
            ;
            ;
        }
        


          Update()
        {
              + id +  + 
                      lname +  + fname + 
                      ;
        }
        


          Add()
        {
              + id +  + 
                      lname +  + fname + 
                      ;
        }
        


          Delete()
        {
              + id +  + 
                      lname +  + fname + 
                      ;
        }
        


          Search()
        {
              + id +  + 
                      lname +  + fname + 
                      ;
        }

        


        

        

        

        


           CalculateWage();
        
    }
}
Interface Employee
Collapse | Copy Code
 System;


 AbstractsANDInterfaces
{
    


    

    

      IEmployee
    {
        


        
        
        
        


        

        

        

        


         ID
        {
            ;
            ;
        }

         FirstName
        {
            ;
            ;
        }
        
         LastName
        {
            ;
            ;
        }
        
        


        

        

        


         Update();

         Add();

         Delete();

         Search();

         CalculateWage();
    }
}
Inherited Objects

Emp_Fulltime:

Collapse | Copy Code
 System;

 AbstractsANDInterfaces
{
    


    

    

     
    

      Emp_Fulltime : Employee
    {
        


        

        


         Emp_Fulltime()
        {
        }


           ID
        {
            

            {
                 id;
            }
            
            {
                id = value;
            }
        }
        
           FirstName
        {
            

            {
                 fname;
            }
            
            {
                fname = value;
            }
        }

           LastName
        {
            

            {
                 lname;
            }
            
            {
                lname = value;
            }
        }

        

        

           Add()
        {
             .Add();
        }
        


        

           Delete()
        {
             .Delete();
        }
        


        

           Search()
        {
             .Search();
        }
        


        

           Update()
        {
             .Update();
        }
        
        


        

        

           CalculateWage()
        {
              + 
                  .fname +  + 
                  ;
        }
    }
}

Emp_Fulltime2:

Collapse | Copy Code
 System;

 AbstractsANDInterfaces
{
    

    


    

    
    

      Emp_fulltime2 : IEmployee
    {
        


        

          id;
          lname;
          fname;

         Emp_fulltime2()
        {
            


            

            

        }

          ID
        {
            

            {
                 id;
            }
            
            {
                id = value;
            }
        }
        
          FirstName
        {
            
            {
                 fname;
            }
            

            {
                fname = value;
            }
        }

          LastName
        {
            
            {
                 lname;
            }
            
            {
                lname = value;
            }
        }

        


        

        

        

          Add()
        {
              + 
                          fname + ;
        }

          Delete()
        {
              + 
                        fname + ;
        }

          Search()
        {
              + 
                       fname + ;
        }

          Update()
        {
              + 
                        fname + ;
        }
        
        


        

        

        

          CalculateWage()
        {
              + 
                  fname +  + 
                  ;
        }
    }
}

Code for Testing

Collapse | Copy Code




  InterfaceExample_Click( sender, 
                                System.EventArgs e)
{
    

    {

        IEmployee emp;

        Emp_fulltime2 emp1 =  Emp_fulltime2();

        emp =  emp1;
        emp.ID = ;
        emp.FirstName=  ;
        emp.LastName =  ;
        


        MessageBox.Show(emp.Add().ToString());
        
        

        MessageBox.Show(emp.CalculateWage().ToString());


    }
    (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }

}

  cmdAbstractExample_Click( sender, 
                                   System.EventArgs e)
{

    Employee emp;

    emp =  Emp_Fulltime();
    

    emp.ID = ;
    emp.FirstName=  ;
    emp.LastName =  ;
    MessageBox.Show(emp.Add().ToString());

    


    MessageBox.Show(emp.CalculateWage().ToString());

}

Conclusion

In the above examples, I have explained the differences between an abstract class and an interface. I have also implemented a demo project which uses both abstract class and interface and shows the differences in their implementation.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

----------------------------------------------------------------------------------------------------------------------

引自:

http://en.csharp-online.net/Interfaces_and_Abstract_Classes

Summary

  • An Interface cannot implement methods.
  • An abstract class can implement methods.
  • An Interface can only inherit from another Interface.
  • An abstract class can inherit from a class and one or more interfaces.
  • An Interface cannot contain fields.
  • An abstract class can contain fields.
  • An Interface can contain property definitions.
  • An abstract class can implement a property.
  • An Interface cannot contain constructors or destructors.
  • An abstract class can contain constructors or destructors.
  • An Interface can be inherited from by structures.
  • An abstract class cannot be inherited from by structures.
  • An Interface can support multiple inheritance.
  • An abstract class cannot support multiple inheritance.

转载于:https://www.cnblogs.com/Jessy/archive/2010/10/28/1863433.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值