Abstract class vs interface | abstract class vs Interface

Source: Internet
Author: User
Document directory
  • Code for testing

Original post address: http://www.codeproject.com/KB/cs/abstractsvsinterfaces.aspx

Original Author:Rahman Mahmoodi

Translation: 54sun

Introduction | description

I will discuss abstract class and interface through this article and the attached demo program ). These two concepts often confuse beginners of the object-oriented language. Therefore, I try to explain their differences in theory and their differences in use. Finally, I use the C # language to demonstrate how to use them.

Background | background

An abstract class without any implementation seems to be no different from an interface! However, abstract classes and interfaces differ much from each other. Let's take a look at their similarities and differences.

What is an abstract class? | What is an abstract class?

Abstract classes are special classes that cannot be instantiated. So we need a class that cannot generate objects? It is very simple. It exists to generate sub-classes. In other words, it can only run other classes to inherit it, and it does not own its own objects (also called instances ). The benefit is that you can implement a hierarchy like parent class subclass. In short, an abstract class is equivalent to a contract, so that all subclasses are forced to implement the same structure or standard.

What is an interface? | What is an interface?

The interface is not a class. It is an entity defined by the keyword interface ). An interface is not implemented. It only defines the declaration of a function (or a method, the same below), but does not define the function implementation. It has something in common with the abstract class: it is also a contract that regulates sub-classes (the function name, return value, and parameter it declares ). The main difference is that a class can implement multiple interfaces but can inherit only one parent class. Therefore, C # does not support multiple inheritance as C ++ does, and interfaces can be used to solve this problem.

Both together | both

When we declare an interface, we declare a group of functions-these must be implemented by some classes. The advantage of doing so is that it provides a way to divide a class into two parts: one is inherited, and the other is obtained through interfaces.

 

When we declare an abstract class, it is equivalent to declaring a basic class -- it may already provide specific implementations of some functions, but at least one function must be not defined. Its purpose is to define what its sub-classes can do, and how to do it is left to the sub-classes for implementation.

 

The following table compares the similarities and differences between interfaces and abstract classes:

 

Feature | feature

Interface | Interface

Abstract class | abstract class

Multiple inheritance

Multi-Inheritance

A class can inherit (implement) multiple interfaces.

A class can inherit only one parent class.

Default implementation

Default implementation

The interface cannot provide function implementation, but can only provide function definition.

Abstract classes can provide complete function implementations or only cover the information of the parent class functions in the subclass.

Access modfiers

Access Modifier

The interface cannot be modified with an access controller, and neither function nor attribute can be modified. All members are considered public. Abstract classes can be modified by using access controllers for their members (functions, attributes, and so on.

Core vs peripheral

Core vs perimeter

An interface is usually used to define the peripheral attributes of a class. In other words, both people and vehicles can implement the 'mobile' interface.

Abstract Classes define the core attributes of a class, that is, the essential attributes of the class objects.

Homogeneity

Homogeneity

If the implementation of various functions only has the same function name, it is best to implement it through the interface.

If the implementation of various functions is similar and has the same behavior, it is better to use abstract classes.

Speed

Speed

It takes more time to determine the class of the function to be called. It should be the case that the function is accessed through an interface object)

Fast

Adding Functionality (Versioning)

Scalability (Version Upgrade)

If we add a new function to the interface, we must check the classes of all implemented interfaces to ensure that each class using the interface implements the newly added function.

If we add a new function to the abstract class and provide a default implementation for this function, all the subclasses of this class can still work normally ..

Fields and constants

Variable fields and constants

No variables or constants can be defined in the interface.

Abstract classes can contain variable fields and constants.

 

Using the code | code

Let me explain the code: I have defined an abstract class.Employee and oneIn the code, I also use annotations to illustrate their differences. I also tested them by generating their instances: we inherit the abstract classGetEmp_fulltime; ImplementationInterfaceIemployeeEmp_fulltime2. Then we generate the objects (instances) of these two sub-classes, assign values to their attributes, and then callcalculateWageTo demonstrate how to use them.

 

Abstract class employee

Using system; <br/> namespace using actsandinterfaces <br/> {<br/> /// <br/> // summary description for employee. <br/> // </P> <p> public abstract class employee <br/> {<br/> // We can have fields and properties <br/>/ /In the abstract class <br/> protected string ID; <br/> protected string lname; <br/> protected string fname; <br/> // properties <br/> public abstract string id <br/>{< br/> get; <br/> set; <br/>}< br/> public abstract string firstname <br/>{< br/> get; <br/> set; <br/>}</P> <p> public abstract string lastname <br/>{< br/> get; <br/> set; <br/>}< br/> // completed methods <br/> Public String Update () <br/> {<br/> return "employee" + ID + "" + <br/> lname + "+ fname + <br/>" updated "; <br/>}< br/> // completed methods <br/> Public String add () <br/> {<br/> return "employee" + ID + "" + <br/> lname + "+ fname + <br/>" added "; <br/>}< br/> // completed methods <br/> Public String Delete () <br/> {<br/> return "employee" + ID + "" + <br/> lname + "+ fname + <br/>" deleted "; <br/>}< br/> // completed methods <br/> Public String search () <br/> {<br/> return "employee" + ID + "" + <br/> lname + "+ fname + <br/>" found "; <br/>}< br/> // abstract method that is different <br/> // from fulltime and contractor <br/> // Therefore I keep it uncompleted and <br // Let each implementation <br/> // complete it the way they calculate the wage. <br/> public abstract string calculatewage (); </P> <p >}< br/>}

Interface employee

Using system; <br/> namespace using actsandinterfaces <br/>{< br/> /// <summary> <br/> // summary description for iemployee. <br/> // </Summary> <br/> Public interface iemployee <br/> {<br/> // cannot have fields. uncommenting <br/> // will raise error! <Br/> // protected string ID; <br/> // protected string lname; <br/> // protected string fname; <br/> // just signature of the properties <br/> // and methods. <br/> // setting a rule or contract to be <br/> // followed by implementations. <br/> string id <br/>{< br/> get; <br/> set; <br/>}< br/> string firstname <br/>{< br/> get; <br/> set; <br/>}</P> <p> string lastname <br/>{< br/> get; <br/> set; <br/>}</P> <p> // cannot have implementation <br/> // cannot have modifiers Public <br/>/etc all are assumed public <br // cannot have virtual <br/> string Update (); <br/> string add (); <br/> string Delete (); <br/> string search (); <br/> string calculatewage (); <br/>}< br/>}

Inherited objects

Emp_Fulltime:

Using system; <br/> namespace using actsandinterfaces <br/> {<br/> /// <br/> // summary description for emp_fulltime. <br/> // </P> <p> // inheriting from the abstract class <br/> public class emp_fulltime: employee <br/> {<br/> // uses all the properties of the <br/> // abstract class therefore no <br/> // properties or fields here! <Br/> Public emp_fulltime () <br/>{< br/>}< br/> Public override string id <br/>{< br/> Get <br/>{< br/> return ID; <br/>}< br/> set <br/>{< br/> id = value; <br/>}</P> <p> Public override string firstname <br/>{< br/> Get <br/>{< br/> return fname; <br/>}< br/> set <br/> {<br/> fname = value; <br/>}< br/> Public override string lastname <br/>{< br/> Get <br/>{< br/> return lname; <br/>}< br/> set <br/> {<br/> lname = value; <br/>}< br/> // common methods that are <br/> // implemented in the abstract class <br/> Public New String add () <br/>{< br/> return base. add (); <br/>}< br/> // common methods that are implemented <br/> // In the abstract class <br/> Public New String Delete () <br/>{< br/> return base. delete (); <br/>}< br/> // common methods that are implemented <br/> // In the abstract class <br/> Public new string search () <br/>{< br/> return base. search (); <br/>}< br/> // common methods that are implemented <br/> // In the abstract class <br/> Public New String Update () <br/>{< br/> return base. update (); <br/>}</P> <p> // abstract method that is different <br/> // from fulltime and contractor <br/> // Therefore I override it here. <br/> Public override string calculatewage () <br/> {<br/> return "full time employee" + <br/> base. fname + "is calculated" + <br/> "using the abstract class... "; <br/>}< br/>}

Emp_Fulltime2:

Using system; <br/> namespace using actsandinterfaces <br/> {<br/> /// <br/> // summary description for emp_fulltime2. <br/> /// </P> <p> // implementing the interface <br/> public class emp_fulltime2: iemployee <br/>{< br/> // all the properties and <br/> // fields are defined here! <Br/> protected string ID; <br/> protected string lname; <br/> protected string fname; <br/> Public emp_fulltime2 () <br/> {<br/> // todo: add constructor logic here <br/> // <br/>}< br/> Public String id <br/>{< br/> Get <br/>{< br/> return ID; <br/>}< br/> set <br/>{< br/> id = value; <br/>}</P> <p> Public String firstname <br/>{< br/> Get <br/>{< br/> return fname; <br/>}< br/> set <br/> {<br/> fname = value; <br/>}< br/> Public String lastname <br/>{< br/> Get <br/>{< br/> return lname; <br/>}< br/> set <br/> {<br/> lname = value; <br/>}< br/> // all the manipulations including add, delete, <br/> // search, update, calculate are done <br/> // within the object as there are not <br/> // implementation in the interface entity. <br/> Public String add () <br/> {<br/> return "fulltime employee" + <br/> fname + "added. "; <br/>}< br/> Public String Delete () <br/> {<br/> return" fulltime employee "+ <br/> fname +" deleted. "; <br/>}< br/> Public String search () <br/> {<br/> return" fulltime employee "+ <br/> fname +" searched. "; <br/>}< br/> Public String Update () <br/> {<br/> return" fulltime employee "+ <br/> fname +" updated. "; <br/>}</P> <p> // if you change to calculatewage (). <br/> // just small 'W' it will raise <br/> // error as in interface <br/> // It is calculatewage () with capital 'W '. <br/> Public String calculatewage () <br/> {<br/> return "full time employee" + <br/> fname + "caluculated using" + <br/> "interface. "; <br/>}< br/>}

Code for testing

// This is the sub that tests both <br/> // implementations using interface and abstract <br/> private void interfaceexample_click (Object sender, <br/> system. eventargs e) <br/>{< br/> try <br/>{< br/> iemployee EMP; <br/> emp_fulltime2 emp1 = new emp_fulltime2 (); <br/> EMP = emp1; <br/> EMP. id = "2234"; <br/> EMP. firstname = "Rahman"; <br/> EMP. lastname = "Mahmoodi"; <br/> // call add method od the object <br/> MessageBox. show (EMP. add (). tostring (); </P> <p> // call the calculatewage method <br/> MessageBox. show (EMP. calculatewage (). tostring (); <br/>}< br/> catch (exception ex) <br/>{< br/> MessageBox. show (ex. message); <br/>}< br/> private void authentication using actexample_click (Object sender, <br/> system. eventargs e) <br/>{< br/> employee EMP; <br/> EMP = new emp_fulltime (); </P> <p> EMP. id = "2244"; <br/> EMP. firstname = "Maria"; <br/> EMP. lastname = "robinlius"; <br/> MessageBox. show (EMP. add (). tostring (); <br/> // call the calculatewage method <br/> MessageBox. show (EMP. calculatewage (). tostring (); <br/>}

 

Conclusion | conclusion

Through the above example, I explained the differences between abstract classes and interfaces, and demonstrated how to use abstract classes and interfaces through a demo program.

 

License

This article and the attached Code comply with: the Code project open license (cpol)

 

........................................................................................................................ ................................................

Why is the layout good, but the display is different...

 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.