"Restudying" C # abstract class abstraction and interface interface

Source: Internet
Author: User

1. What is abstract class

First look at MSDN for abstract class descriptions:

Abstract classes are classes that leave some or all of the members that are not implemented so that the implementation can be provided by a derived class.

In object-oriented programming, abstract classes are used as base classes for hierarchies and represent common functionality for groups of different object types. as the name "abstract" implies, abstract classes typically do not correspond directly to specific entities in the problem domain. abstract classes, however, represent the similarities between several different concrete entities.

Classes are treated as abstract classes only if there are abstract methods that are declared but not defined. Therefore, classes that have abstract methods are not necessarily abstract classes. Do not use the AbstractClass attribute unless the class has an abstract method that is not defined.

A class can inherit from only one abstract (or any other type) class.

What is that abstraction? For example: Cars, trucks, electric cars can be abstracted as cars, helicopters, aircraft, fighter jets, can be abstracted into aircraft, and cars and airplanes, can be abstracted into vehicles, gradually off the "personality", to retain the "commonality", which is the abstraction, which is also part of object-oriented polymorphism inheritance.

abstract classes should be used instead of derived classes when a class is abstracted into its methods that need to be implemented in subclasses. For example: helicopters and passenger aircraft, can fly, but before inheriting, you do not know whether the aircraft use propeller fly, or use turbofan engine fly, so can only abstract into abstract class.

2. What is an interface

Let's look at MSDN's description first:

An interface contains a class or struct that can implement a definition of a set of functions.

Because the C # language does not support multiple inheritance, there are several excuses that can be implemented, so this feature is important.

An interface cannot contain constants, fields, operators, instance constructors, destructors, or types. Interface members will automatically be public, so they will not contain any access modifiers. Members also cannot be static.

To implement an interface member, the corresponding member of the implemented class must be public, non-static, and have the same name and signature as the interface member.

Childhood played jigsaw puzzles, each small picture through the buckle connected together to become a picture, this small buckle is very image of the "interface", a huge system, but also through the interface of each module together.

It can be understood that an interface is a class that implements the method conventions of the outside world, so that we know that this class must have a way to achieve our needs.

For example: We all know that the car has "throttle", we do not have to control whether the car is electric or gasoline or diesel, no matter what advanced or low-level engine, as long as the foot, the car can be moved, the external sector, "throttle" is equivalent to an interface, the car realized this interface, We knew we could start the car by stepping on the accelerator. If one day the bicycle also achieved the "throttle", we also do not care so much how the inside of the bicycle is how to achieve (I do not want to know and do not need to know, for consumers, and I have nothing to do with), anyway, pedal bicycle throttle, bicycle will definitely move up.

so An interface is a method convention that has a universal "commonality".

3. When to use abstract classes, interfaces?

Look directly at a section of the code scenario with "hard disk" as abstract:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceabstractandinterface{/// <summary>    ///Universal USB interface, plugged into the computer, the computer only recognize this method, to read the data inserted into things, for other things regardless/// </summary>     Public InterfaceUsb_interface {stringUsbreaddata (); }    /// <summary>    ///Universal Bluetooth interface, after turning on Bluetooth, the computer only recognize this method, to read the data inserted into things, for other things regardless/// </summary>     Public InterfaceBluetooth_interface {stringBluetoothreaddata (); }    /// <summary>    ///hard Drive abstract class/// </summary>     Public Abstract classDisk {//abstract method read data, because the subclass reading method cannot be determined (HDD disk seek, SSD flash particles directly read), so declare abstract function, then this class must be declared as abstract class.          Public Abstract stringReadData (); }    /// <summary>    ///interface for transmitting data via USB and Bluetooth/// </summary>     Public classSsd_disk:disk, Usb_interface, bluetooth_interface { Public Override stringReadData () {return "SSD Ultra-high-speed read data through flash particles! "; }         Public stringUsbreaddata () {return "data transfer via USB:"+ReadData (); }         Public stringBluetoothreaddata () {return "data transfer via Bluetooth:"+ReadData (); }    }    /// <summary>    ///interface for transmitting data via USB and Bluetooth/// </summary>     Public classHdd_disk:disk, Usb_interface, bluetooth_interface { Public Override stringReadData () {return "HDD reads data through magnetic discs! "; }         Public stringUsbreaddata () {return "data transfer via USB:"+ReadData (); }         Public stringBluetoothreaddata () {return "data transfer via Bluetooth:"+ReadData (); }    }     Public classComputer {/// <summary>        ///The computer just reads the data through the interface, no matter what device you are, return the data to me anyway. /// </summary>        /// <param name= "Usbdevice" > Device for USB interface </param>        /// <returns></returns>         Public stringReadusb (Usb_interface usbdevice) {returnUsbdevice.usbreaddata (); }    }    classProgram {Static voidMain (string[] args) {Usb_interface SSD=NewSsd_disk (); Usb_interface HDD=NewHdd_disk (); Computer Computer=Newcomputer (); Console.WriteLine (computer.            READUSB (SSD)); Console.WriteLine (computer.        READUSB (HDD)); }    }}

My summary of the above code is as follows:

1, Computer class through the Usb_interface to read the device data, so this USB device for computer class is transparent (disk no exposure), computer do not need to know the specific class, only know to call this interface, you return to my data on the line, Increase cohesion, low coupling, otherwise, if there is a new storage device that is not inherited from disk class, computer class is not to write a new method to read the data?

2, through the interface, we can easily extend the function of the class and functional combination. Otherwise, using abstract classes, more than one function will inherit one time, the code work is very large, sub-class division is very not obvious

For example:

    /// <summary>    ///hard Drive abstract class/// </summary>     Public Abstract classDisk {//abstract method read data, because the subclass reading method cannot be determined (HDD disk seek, SSD flash particles directly read), so declare abstract function, then this class must be declared as abstract class.          Public Abstract stringReadData (); }     Public Abstract classUsbdisk:disk { Public Abstract stringUsbreaddata (); }     Public Abstract classBluetoothdisk:disk { Public Abstract stringBluetoothreaddata (); }     Public Abstract classBluetoothandusbdisk:disk { Public Abstract stringUsbreaddata ();  Public Abstract stringBluetoothreaddata (); }

The inheritance of disk products with 3 different functions (classes can only be inherited), which is already complicated by the lack of implementation, is even more complicated if you want to implement SSDs and HDDs separately.

At the beginning of the design should be found that the USB and Bluetooth in fact and disk is not too much association ( is the universal product has the "common" method convention ), it is an external data communication method, should be extracted as an interface. However, if it is a method of data flow between two parts within disk (the subclass is implemented differently), it can be defined as an abstract function.

3, interface programming, if one day to jump out of a new storage device, the computer does not have to make any changes (new device principle I do not care, anyway I call the interface, you will return to my data), you can also directly read the new device data (in fact, the principle of USB universal interface is also the case).

Finally, take a look at the summary on MSDN:

    • If you expect to create multiple versions of a component, create an abstract class. Abstract classes provide a simple way to control the component version. By updating the base class, all inherited classes are automatically updated with the changes. On the other hand, the interface cannot be changed once it is created. If a new version of the interface is required, a completely new interface must be created.
    • If you create a feature that will be used across a wide range of heterogeneous objects, the interface is used. Abstract classes should be used primarily for closely related objects, and interfaces are best suited to provide common functionality for unrelated classes.
    • If you want to design a small and concise function block, use the interface. If you are designing large functional units, use an abstract class.
    • Use an abstract class if you want to provide common, implemented functionality across all implementations of a component. Abstract classes allow partial implementations of classes, and interfaces do not contain implementations of any members.

"Restudying" C # abstract class abstraction and interface interface

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.