C # abstract classes and interfaces

Source: Internet
Author: User

What is the difference between an abstract class and an interface? Why do you need an interface with an abstract class?

Interfaces and abstract classes of the same point is not instantiated, the difference is that the method in the interface has no method body, and abstract class is not, except the abstract method has no method body, other methods have method body.

The reason: In C #, a class can inherit only one class, but it can inherit multiple interfaces.

Abstract class:

1. Cannot be instantiated

2. The abstract method must be overridden by the quilt class

3. If the class contains an abstract method, the class must be defined as an abstract class

Abstract before class.

Abstract methods are added before the return value, with no method body, and a semicolon is added directly after the parentheses.

1. Classes containing abstract methods must be abstract classes

2. Abstract classes do not necessarily contain abstract methods

A virtual method is used to implement polymorphism, in order for an instance of a subclass to completely replace a member from a parent class, the parent class must declare the member as virtual, which is accomplished by adding the virtual keyword before the member's access type.

Subclasses can choose to use the Override keyword to replace the parent class implementation with its own implementation, which is the method override, and of course it can not be overridden.

classanimal{ Public Virtual voidShout () {Console.WriteLine ("Animal Bark! "); }}classcat:animal{ Public Override voidShout () {Console.WriteLine ("The cat barks! "); }}classdog:animal{ Public Override voidShout () {Console.WriteLine ("Dog Bark! "); }}classprogram{Static voidMain (string[] args) {animal[] Animals=Newanimal[2]; animals[0]=NewCat (); animals[1]=NewDog (); foreach(varAnimalinchanimals) {Animal.        Shout ();    } console.readline (); }}

C # abstract classes and interfaces

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.