Abstract, virtual, override, New Keyword usage

Source: Internet
Author: User

To put it simply, let's talk about msdn.

Virtual: contains the function body. The inherited class does not need to be rewritten. Of course, it can also be rewritten;
Abstract: The inherited class must be overwritten because it does not contain the function body;
New: the general method that the inheritance class wants to overwrite. The new keyword is used;

 

Using System;
Using System. Collections. Generic;
Using System. text;

Namespace Keywords
{
Public   Abstract   Class Shapeclass
{
Public   String Getshapename ()
{
Return "Shape class";
}

Public   Abstract   Int Area ();

Public   Virtual   Int Volume ()
{
Return 11;
}

}

Public   Class Square: shapeclass
{
// Use the New Keyword to override the general method of the base class
Public   New   String Getshapename ()
{
Return "Square";
}

// Must be rewritten
Public   Override   Int Area ()
{
Return 22;
}

// It can be rewritten or not rewritten.
Public   Override   Int Volume ()
{
//Return base. Volume ();
Return 33;
}
}

Public   Class Program
{
Public   Static   Void Main ( String [] ARGs)
{
Square= NewSquare ();
Console. writeline (square. getshapename ());
Console. writeline (square. Area ());
Console. writeline (square. Volume ());

Console. Readline ();
}
}
}

 

Appendix: msdn Introduction

 

Abstract modifiers can be used with classes, methods, attributes, indexers, and events. Use the abstract modifier in the class declaration to indicate that a class can only be the base class of other classes. Members marked as abstract or included in an abstract class must be implemented through classes derived from the abstract class.

In this exampleSquareRequiredAreaBecause it is derived fromShapesclass:

  CopyCode
Abstract class shapesclass {Abstract Public int area ();} class square: shapesclass {int X, Y; // not providing an Area Method Results // In a compile-time error. public override int area () {return x * Y ;}}

For more information about abstract classes, see abstract classes, seal classes, and class members (C # programming guide ).

Remarks

Abstract classes have the following features:

    • Abstract classes cannot be instantiated.

    • Abstract classes can contain abstract methods and abstract accessors.

    • You cannot use the sealed (C # reference) modifier to modify the abstract class, which means that the abstract class cannot be inherited.

    • A non-abstract class derived from an abstract class must include all the inherited abstract methods and the actual implementation of the abstract accessors.

Use the abstract modifier in a method or attribute declaration to indicate that a method or attribute does not contain an implementation.

Abstract methods have the following features:

    • The abstract method is an implicit virtual method.

    • Only abstract methods can be declared in abstract classes.

    • The abstract method declaration does not provide actual implementation, so there is no method body. The method declaration ends with a semicolon and there is no braces ({}) after the signature ({}). For example:

        Copy code
      Public abstract void mymethod ();

    • The implementation is provided by an override method, which is a non-abstract class member.

    • It is incorrect to use the static or virtual modifier in the abstract method declaration.

Except for the differences in the declaration and call syntax, abstract attributes behave the same way as abstract methods.

    • It is incorrect to use the abstract modifier for static attributes.

    • In a derived class, you can override abstract inheritance attributes by including the attribute declaration using the override modifier.

Abstract classes must be implemented for all interface members.

Abstract classes that implement interfaces can map interface methods to abstract methods. For example:

  Copy code
Interface I {void M ();} abstract class C: I {public abstract void M ();}

Example

In this example,DerivedclassClass is from the abstract classBaseclassDerived. An abstract class contains an abstract method.AbstractmethodAnd two abstract attributesXAndY.

  Copy code
// Abstract_keyword.cs // abstract classes using system; abstract class baseclass // abstract class {protected int _ x = 100; protected int _ y = 150; public abstract void abstractmethod (); // abstract method public abstract int X {Get;} public abstract int y {Get ;}} class derivedclass: baseclass {public override void abstractmethod () {_ x ++; _ y ++;} public override int x // overriding property {get {return _ x + 10 ;}} public override int y // overriding property {get {return _ y + 10 ;}} static void main () {derivedclass o = new derivedclass (); O. abstractmethod (); console. writeline ("x = {0}, y = {1}", O. x, O. Y );}}

Output

 
X = 111, y = 161
Note

In the preceding example, if you try to instantiate an abstract class by using the following statement:

  Copy code
Baseclass BC = new baseclass (); // Error

An error occurs, indicating that the compiler cannot create an instance of the abstract class "baseclass.

 

Virtual keywords are used to modify methods, properties, indexers, or event declarations, and allow them to be rewritten in a derived class. For example, this method can be overwritten by any class that inherits it.

  Copy code
Public Virtual double area () {return x * Y ;}

The Implementation of Virtual members can be changed by the override member in the derived class. For more information about using virtual keywords, see using override and new keywords to control versions (C # Programming Guide) and learn when to use override and new keywords (C # programming guide ).

Remarks

When a virtual method is called, The system checks the runtime type of the object for the override member. This override member in most Derived classes will be called. If no derived class is used to override this member, it may be the original member.

By default, the method is non-virtual. You cannot override non-virtual methods.

Virtual modifiers cannot be used with static, abstract, and override modifiers.

Except for the declaration and call syntax, the virtual attribute behavior is the same as that of the abstract method.

    • It is incorrect to use the virtual Modifier on static attributes.

    • You can override a virtual inheritance attribute in a derived class by using the override modifier.

Example

In this example,DimensionsClass inclusionXAndYTwo coordinates andArea ()Virtual method. Different Shape classes, suchCircle,CylinderAndSphereInheritanceDimensionsClass, and calculate the surface area for each graph. Each derived class has its ownArea ()Rewrite implementation. According to the object associated with this method, by calling the correctArea ()Implementation,ProgramCalculate and display the correct area for each graph.

In the previous example, pay attention to the inherited classCircle,SphereAndCylinderAll use constructors that initialize the base class, for example:

  Copy code
Public cylinder (Double R, double H): Base (R, h ){}

This is similar to the initialization list of c ++.

  Copy code
// Cs_virtual_keyword.cs using system; Class testclass {public class dimensions {public const double Pi = math. pi; protected Double X, Y; Public dimensions () {} public dimensions (Double X, Double Y) {This. X = x; this. y = y;} Public Virtual double area () {return x * Y;} public class circle: Dimensions {public circle (Double R): Base (R, 0) {} public override double area () {return pI * x * X;} class sphere: Dimensions {public sphere (Double R): Base (R, 0) {} public override double area () {return 4 * pI * x * X;} class cylinder: Dimensions {public cylinder (Double R, double H): Base (r, h) {} public override double area () {return 2 * pI * x + 2 * pI * x * Y;} static void main () {double r = 3.0, H = 5.0; Dimensions c = new circle (r); dimensions S = new sphere (r); dimensions L = new cylinder (R, H ); // Display Results: console. writeline ("area of Circle = {0: F2}", C. area (); console. writeline ("area of Sphere = {0: F2}", S. area (); console. writeline ("area of cylinder = {0: F2}", L. area ());}}

Output

 
Area of Circle = 28.27 area of Sphere = 113.10 area of cylinder = 150.80

 

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.