The difference between interface and abstract class in C #

Source: Internet
Author: User
Tags define abstract



1) When inheriting an abstract class, each of the abstract methods in the class must be overridden, and each implemented method must receive the same number and type of parameters as the method specified in the abstract class, with the same return value, which is the same as the interface.  2) When a parent class already has a method that is actually functional, the method can be used in a subclass without having to implement it, directly referencing the method, and the subclass can override the method of the parent class (the concept of inheritance).  3) when implementing (implement) an interface (interface), it is necessary to implement all the methods defined in the interface, and not to omit any one.  4) In addition, an abstract class cannot produce an object, but it can be declared by its implementation class.


A. Both are abstract classes and cannot be instantiated.
B. Interface implementations and ABSTRCT class subclasses must implement an abstract method that has already been declared. 2. Different
A. Interface need to be implemented, use implements, and abstract class need to inherit, use extends.
B. A class can implement multiple interface, but a class may inherit only one abstract class.
C. Interface emphasizes the implementation of a particular feature, while the abstract class emphasizes its affiliation.
D. Although the subclasses of the interface implementation class and the ABSTRCT class must implement the corresponding abstract methods, the implementations are in different forms. Each method in interface is an abstract method, all just declared (declaration, no method body), the implementation class must be implemented. The subclass of abstract class can be implemented selectively. This option has a two-point implication:
One is that not all methods in the Abastract class are abstract, only those whose crown has an abstract are abstracted, and subclasses must be implemented. For those that do not have an abstract method, the method body must be defined in the ABSTRCT class.
The second is that when the subclass of abstract class inherits it, it can either inherit directly from the non-abstract method or overwrite it, but the abstract method can be implemented by choice, or it can be implemented by declaring its method abstract, without implementing it and leaving it to its subclasses, but this class must also be declared as an abstract class. Abstract classes, and of course, cannot be instantiated.
E. Abstract class is an intermediary between interface and class.
Interface are completely abstract, can only declare methods, and can only declare pulic methods, cannot declare private and protected methods, cannot define method bodies, and cannot declare instance variables. However, interface can declare constant variables, and this example is not hard to find in the JDK. But putting constant variable in interface violates its purpose of being an interface, and it confuses the different value of interface and class. If you really need it, you can put it in the appropriate abstract class or class.
Abstract class plays a connecting role in interface and class. On the one hand, abstract class is abstract and can be used to declare abstractions to standardize the functions that subclasses must implement, on the other hand, it can define the default method body for the subclasses to use or overwrite directly. In addition, it can define its own instance variables for use by subclasses through inheritance. 3. Interface applications
A. Classes and classes require a specific interface to reconcile, rather than how they are implemented.
B. As an identity that is capable of implementing a specific function, it can also be a purely identifying interface method that does not exist.
C. A set of classes needs to be treated as a single class, and the caller is only connected to this set of classes through an interface.
D. A specific number of functions need to be implemented, and there may be no connection between these features at all. 4. Application of abstract class
In a word, it can be used in situations where both a uniform interface is required and an instance variable or a default method is required. The most common are:
A. Defines a set of interfaces, but does not want to force each implementation class to implement all interfaces. You can use the abstract class to define a set of method bodies, even an empty method body, and then select the methods that you are interested in to overwrite by subclasses.
B. In some cases, a purely interface does not satisfy the coordination between classes and classes, and the variables that represent states in a class must differentiate between different relationships. Abstract mediation can be a good way to meet this point.
C. Standardize a set of mutually coordinated methods, some of which are common, state-independent, shareable, and do not need subclasses to implement separately, while others require individual subclasses to implement specific functions according to their own specific state. 


Concept Introduction





What is an interface?





An interface is an abstract type that contains a set of virtual methods, each of which has its name, parameters, and return values. An interface method cannot contain any implementation, and the CLR allows an interface to contain events, properties, indexers, static methods, static fields, static constructors, and constants. However, note that C # cannot contain any static members. A class can implement multiple interfaces, and when a class inherits an interface, it not only implements all the methods defined by that interface, but also implements all the methods that the interface inherits from the other interfaces.





The definition method is:





The following is the referenced content:
public interface System.IComparable
{
int CompareTo (object o);
}
public class Testcls:icomparable
{
Public Testcls ()
{
}






private int _value;
public int Value
{
get {return _value;}
set {_value = value;}
}






public int CompareTo (object o)
{





Use as mode for transformational judgment
Testcls aCls = o as testcls;
if (aCls! = null)
{





Implementing an abstract method
Return _value.compareto (Acls._value);
}
}
}





What is an abstract class?





Abstract classes provide multiple derived classes that share a common definition of a base class that can provide either an abstract method or a non-abstract method. Abstract classes cannot be instantiated, and they must be implemented by derived classes to implement their abstract methods, so the new keyword cannot be used for abstract classes and cannot be sealed. If a derived class does not implement all of the abstract methods, the derived class must also be declared as an abstract class. In addition, the implementation of abstract methods is implemented by the overriding method.





The definition method is:





The following is the referenced content:
<summary>
Defining abstract Classes
</summary>
Abstract public class Animal
{
Defining static fields
static protected int _id;
Defining properties
public abstract static int Id
{
Get
Set
}






Defining methods
public abstract void Eat ();





Defining indexers
public string This[int i]
{
Get
Set
}
}





<summary>
Implementing abstract Classes
</summary>
public class Dog:animal
{
public static override int Id
{
get {return _id;}
set {_id = value;}
}






public override void Eat ()
{
Console.Write ("Dog Eats.")
}
}





3. Same points and different points





3.1 Identical points





cannot be instantiated directly, it is possible to implement its abstract method through inheritance.
Are the technical basis for abstract programming, and many design patterns have been realized.





3.2 Different points





Interfaces support multiple inheritance, and abstract classes cannot implement multiple inheritance.
An interface can only define abstract rules; an abstract class can define a rule and possibly provide an implemented member.
An interface is a set of behavior specifications; An abstract class is an incomplete class that focuses on the concept of a family.
Interfaces can be used to support callbacks, and abstract classes cannot implement callbacks because inheritance is not supported.
Interfaces contain only the signatures of methods, properties, indexers, events, but cannot define fields and methods that contain implementations; Abstract classes can define fields, properties, and methods that contain implementations.
Interfaces can be used for value types and reference types, and abstract classes can only be used for reference types. For example, a struct can inherit an interface and not inherit a class.





Through the same and different comparisons, we can only say that the interface and abstract classes, strengths, but no advantage. In the actual programming practice, we have to consider the specific circumstances to the discretion, but the following experience and accumulation, may give us some inspiration, in addition to some of my accumulation, many come from the classics, I believe that can withstand the test. So in the rules and occasions, we learn these classics, the most important thing is to apply, of course, I will opinion broad home smile, crossing please continue.





3.3 Rules and occasions





1. Keep in mind that one of the most important principles of object-oriented thinking is interface-oriented programming.
2. With the help of interfaces and abstract classes, many of the ideas in the 23 design patterns have been cleverly implemented, and I think the essence is simply: oriented toward abstract programming.
3. Abstract classes should be used primarily for closely related objects, and interfaces are best suited to provide common functionality for unrelated classes.
4. The interface focuses on the can-do relationship type, while the abstract class is biased to the is-a-type relationship;
5. Interface multi-definition object behavior, abstract class multi-definition object properties;
6. The interface definition can use public, protected, internal, and private modifiers, but almost all of the interfaces are defined as public, so there's no need to say more.
7. "Interface unchanged" is an important factor to be considered. Therefore, when an extension is added by an interface, the new interface should be added, and the existing interface cannot be changed.
8. As far as possible to design the interface into a single functional block, in the. NET framework, for example, IDisposable, IDisposable, IComparable, IEquatable, IEnumerable, and so on, all contain only one public method.
9. The capital letter "I" in front of the interface name is a convention, just as the field names begin with an underscore, adhere to these principles.
10. In the interface, all methods are default to public.
11. You can create an abstract class if you anticipate that a version problem will occur. For example, to create a dog, a chicken (Chicken), and a duck (Duck), you should consider abstracting the animal (Animal) to deal with the possible future of the wind horse cattle. Adding a new member to an interface would force the requirement to modify all derived classes and recompile, so the problem with versioning is best implemented as an abstract class.





12. A non-abstract class derived from an abstract class must include all inherited abstract methods and the actual implementation of the abstract accessor.
13. The New keyword cannot be used for abstract classes, nor can it be sealed, because abstract classes cannot be instantiated.
14. You cannot use the static or virtual modifier in an abstract method declaration.





The above rules, I will be brazen tentative for T14 bar, write so tired, as a temporary reward it. We can also exchange the exchange, I will revise it in time.





4. Classic example





4.1 Absolute Classics





The. NET Framework is the best resource for learning, and a conscious study of the FCL is a required course for every. NET programmer, and I have the following suggestions regarding the use of interfaces and abstract classes in the FCL:





1.FCL uses an interface-based design for the collection class, so please pay attention to the design implementation of the interface in System.Collections.
2.FCL uses abstract class-based design for the data flow related classes, so pay attention to the abstract class design mechanism of the System.IO.Stream class.





4.2 Different dishes





The following example, because it is my understanding, so give the classic "relative" mark, as to when the promotion to "absolute", just look at me. NET pursuit of the road, whether can as always so persistent, so I will be relatively reconstructed to absolute so far (hehe). This example does not describe the application of abstract classes and interfaces in design mode, because that will be another text of discussion value, this article focuses on the concepts and principles, but the real application comes from the specific requirements specification.





Design structure:











1. Defining abstract Classes





The following is the referenced content:
Public abstract class Animal
{
protected string _name;
Declaring abstract properties
Public abstract String Name
{
Get
}





Declaring abstract methods
public abstract void Show ();





Implementing a general approach
public void Makevoice ()
{
Console.WriteLine ("All animals can make voice!");
}
}

2. Defining the interface





The following is the referenced content:
public interface IAction
{
Define public method Labels
void Move ();
}





3. Implementing abstract classes and interfaces





The following is the referenced content:
public class Duck:animal, iaction
{
Public Duck (string name)
{
_name = name;
}
Overloaded abstract methods
public override void Show ()
{
Console.WriteLine (_name + "is showing for you.");
}





Overloading Abstract Properties
public override string Name
{
get {return _name;}
}





Implementing interface Methods
public void Move ()
{
Console.WriteLine ("Duck also can swim.");
}





}





public class Dog:animal, iaction
{
Public Dog (string name)
{
_name = name;
}





public override void Show ()
{
Console.WriteLine (_name + "is showing for you.");
}





public override string Name
{
get {return _name;}
}





public void Move ()
{
Console.WriteLine (_name + "also can run.");
}






}





4. Client implementation





The following is the referenced content:





public class Testanmial
{
public static void Main (string [] args)
{
Animal duck = new Duck ("duck");
Duck. Makevoice ();
Duck. Show ();





Animal dog = new Dog ("Dog");
Dog. Makevoice ();
Dog. Show ();






IAction dogaction = new Dog ("A big Dog");
Dogaction.move ();
}
}

5. The Stone of his mountain





is the so-called truth is everyone to see, so the garden has an innovative point of view in this, one is to thank you for sharing, the second is to improve the opinion of the shortcomings, I hope to be able to form a knowledge of the field, be used for me, to be used in the public.






[url=]dunai[/url] That abstract classes are extracts of specific classes of common divisor, and interfaces are to "hash" some unrelated classes into a common group. As for their syntax in each language, the details of the language are not my main concern.
The collection of the Birch Mountain stream is also very good.
Artech that: The code is shared and extensible, so use the abstract Class as much as possible. Of course the interface in other aspects of the advantages, I think also can not be ignored.
Shenfx the use of interfaces when searching for functional commonalities among objects with large differences, and the use of abstract base classes when seeking functional differences among more common objects.





Finally, MSDN's recommendations are:





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.





6. Conclusion





interface and abstract class, is one of the most discussed topics on the forum and in the classroom, the reason for this old topic to come out again, is because from my experience, a deep understanding of these two object-oriented basic content, for the enliven object-oriented abstract programming idea is very important. This article basically outlines the interface and abstract class concepts, similarities and differences and the use of rules, from a learning point of view, I think these summaries are enough to express its core. But with an in-depth understanding of object-oriented and software design, and based on ongoing practice, Scott says that he insists on writing the demo one hours a day, so should we be more diligent about keyboards. For the interface and abstract class, please use it and know it, and think more about it.



 



The difference between interface and abstract class in C #

Related Article

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.