Usage of static, interface, virtual, abstract, and override in C #

Source: Internet
Author: User
Tags uppercase letter

C # is an object-oriented programming language. Every function belongs to a class.

Static: When a method is declared as static, this method is a static method, and the compiler will keep the implementation of this method during compilation. That is to say, this method belongs to the class but does not belong to any member. no matter whether the class instance exists or not, it will exist. Just like the entry function static
Void main, which can be called directly because it is a static function.

Virtua: When a method is declared as virtual, It is a virtual method until you use classname variable = new
Classname (); before declaring an instance of a class, it does not exist in the real memory space. This keyword is frequently used in class inheritance to provide support for Polymorphism of class methods.
Overrride: Indicates rewriting.
This class inherits from the shape class.
Public override double area must exist in shape, but we do not want to use
So rewrite
Virtual, abstract is to tell other classes that you want to inherit from. You can override this method or attribute of mine. Otherwise, it is not allowed.
A vivid example
: Dad represents the base class (inherited class)
Child represents subclass (inherited class)
Dad told his son via virtual: "Child, you want to inherit my career, and you can continue to develop your own business"
My son told the world with override: "I didn't take my dad directly. He just gave me his path and I struggled for it myself"

Abstract: abstract method declaration is a method that must be overwritten by a derived class. abstract classes are used for inheritance. It can be considered a virtual method without an implemented body. If a class contains abstract methods, classes must be defined as abstract classes, whether or not they contain other general methods. abstract classes cannot have entities.
Example:
Interface: Used to declare an Interface
1. Only some method conventions are provided, and method subjects are not provided.
For example:
Public interface iperson
{
Void
Getname (); // does not contain the method subject
}
2. methods cannot be modified using public abstract, without field variables or constructor.
3. The method can contain parameters.
For example
Public interface iperson
{
Void getage (string
S );
}
Example 1 ):
Public interface iperson
{
Iperson ();
// Error
String name; // Error
Public void getidcard (); // Error
Void getname ();
// Right
Void getage (string S); // right
}
Interface implementation class
1. The format is consistent with that of the inherited class, as shown in figure
Public class Chinese: iperson {}
2. Each method in the interface must be implemented.
Example 2: inheritance Example 1
Public
Class Chinese: iperson
{
Public Chinese () {}// add structure
Public void
Getname () {}// implement getname ()
Public void getage (string s ){}
// Implement getage ()
}
Abstract: declaring abstract classes and abstract methods
1. The class of the abstract method must be an abstract class.
2. abstract classes cannot be directly instantiated and must be implemented by their derived classes.
3. the abstract method does not contain the method subject and must be implemented in override mode by the derived class. This is similar to the method in interface.
For example
Public
Abstract class Book
{
Public book ()
{
}
Public abstract void
Getprice (); // abstract method, excluding subject
Public Virtual void getname ()
// Virtual method, which can overwrite
{
Console. writeline ("this is a test: Virtual
Getname ()");
}
Public Virtual void getcontent ()
// Virtual method, which can overwrite
{
Console. writeline ("this is a test: Virtual
Getcontent ()");
}
Public void getdate ()
// General method. If it is rewritten in a derived class, the new keyword must be used.
{
Console. writeline ("this is a test: void
Getdate ()");
}
}
Public class javatek: Book
{
Public override
Void getprice () // implements the abstract method, which must be implemented
{
Console. writeline ("this is a test: javatek
Override abstract getprice ()");
}
Public override void getname ()
// Overwrite the original method, not required
{
Console. writeline ("this is a test: javatek override
Virtual getname ()");
}
}
The test is as follows:
Public class test
{
Public
Test ()
{
Javatek jbook = new javatek ();
Jbook. getprice ();
// Call getprice () in javatek ()
Jbook. getname ();
// Call getname () in javatek ()
Jbook. getcontent ();
// Call getcontent () in the book ()
Jbook. getdate (); // call getdate () in book ()
}
Public
Static void main ()
{
Test T = new
Test ();
}
}
Virtual: Mark the method as virtual
1. Override this method in a derived class
2. Objects can also be called without Overwriting
3. The method without this mark (or any other mark) needs to be hidden from the original method by new when rewriting.
Abstract
And virtual: override is used for method rewriting.
Keywords
The Interface Definition starts with an uppercase letter I. The method only defines its name. in C #, the method is a public method by default. The public modification method is not allowed; otherwise, a compilation error occurs. The interface can be inherited from other interfaces, if multiple interfaces are inherited, the parent interface list is separated by commas.

Interfaces can be implemented through classes. When the base list of classes contains both the base classes and interfaces, the base classes appear in the list first. Classes must implement their abstract methods;

Interface Usage: see Code (for details)
Interface Usage
Interface Usage (instance 1)
Using system;

Namespace dage. Interface
{
// Printer interface
Public interface iPrint
{

String returnprintname ();
}
}

//--------------------------------------------
Using system;
Using
Dage. interface;
Namespace dage. Print
{
// HP printer
Public class
HP: iPrint
{
Public String returnprintname ()
{
Return
"This is an HP printer ";
}
}
}
//--------------------------------------------

Using system;
Namespace dage. Print
{
// EPS printer type
Public class
EPS: iPrint
{
Public String returnprintname ()
{
Return
"This is an EPS printer ";
}
}
}

//--------------------------------------------
Using system;
Using
Dage. interface;
Namespace dage
{
// Print
Public class printer

{
Public printer ()
{}
Public String printname (iPrint)

{
Return iPrint. returnprintname ();
}
}
}

//--------------------------------------------
-- Winfrom:

Private void button#click (Object sender, system. eventargs E)
{

Printer P = new printer ();
Switch (this. combobox1.text)
{
Case
"HP ":
MessageBox. Show (P. printname (new HP ()));
Break;
Case "EPS ":

MessageBox. Show (P. printname (New EPS ()));
Break;
Default:

MessageBox. Show ("This brand is not found! ");
Break;
}
}

------------------------------------------------------------------------------------------------------------------------------- ------- Static usage

To understand static, you must first understand another relative keyword. Many people may not know this keyword, that is, Auto. In fact, we usually declare variables without static modification, all are auto, because it is default, just as short and long are always int by default; we usually declare a variable:
Int
A;
String
S;
Actually:
Auto
Int;
Auto string
S;
The static variable declaration is:
Static
Int;
Static string
S;
This seems to be more conducive to understanding that auto and static are paired keywords, just like private, protected, and public;
I don't understand static, but I don't understand auto because it is more general. Some things you use every day, but it doesn't necessarily mean you really understand it; auto means that the program automatically controls the life cycle of the variable. It usually means that the variable is allocated when it enters its scope and is released when it leaves its scope; static is not auto, and variables are allocated during program initialization until the program exits. Static is assigned to release variables according to the life cycle of the program, instead of the life cycle of the variable itself; so, for example:
Void
Func ()
{
Int
A;
Static int
B;
}
Every time this function is called, variable A is new because it is allocated when it enters the function body and released when it exits the function body. Therefore, multiple threads call this function, each has its own independent variable A, because it is always re-allocated. Variable B is allocated during program initialization no matter whether you use this function or not, or it is allocated when the declaration is executed for the first time (different compilers may be different), so when multiple threads call this function, they always access the same variable B, this is also important in multi-threaded programming!
All static usage:
1. Static members of the class:
Class
A
{
PRIVATE:
Static
Int
S _;
};
It must be initialized in CPP:
Int
A: S _ = 0 ;//
Note that there is no static modification here!
A static member of a class is a shared member of all instances of the class, that is, a global variable in the category of the class, or a global variable named A: S, it only has class security attributes. The principle is very simple, because it is allocated during program initialization, so it is shared only once;
Static members of a class must be initialized, and the same is true because they are allocated during program initialization, so Initialization is required. Classes are only declared and initialized in CPP, you can place a breakpoint on the initialization code. the breakpoint will be reached before the program executes the first statement of Main. If your static member is a class, the constructor is called;
2. Static functions of the class:
Class
A
{
PRIVATE:
Static
Void func (int
);
};
Static modification is not required during implementation, because static is a declarative keyword;
Static functions of a class are global functions in the category of the class. They cannot be private members of the class, but only static members of the class can be called without class instances. In fact, it is a global function that adds class access permissions: void
A: func (INT );
Static member functions can be inherited and overwritten, but cannot be virtual functions;
3. Only valid global variables in CPP:
Declare within the global scope of the CPP file:
Static
Int g _ =
0;
This variable is valid in this CPP, but other CPP files cannot access this variable. If two CPP files declare Global static variables with the same name, they are actually two independent variables;
If you do not use static to declare global variables:
Int
G _ =
0;
Therefore, it cannot be guaranteed that the variable is not shared by other CPP instances, nor can it be shared by other CPP instances, because multiple CPP instances must share one global variable, it should be declared as extern (external); it is also possible that the compilation will report that the variables are repeatedly defined; in short, such writing is not recommended, and the usage of this global variable is not clear;
If you declare in a header file:
Static
Int g_vaule =
0;
A global variable will be created for each CPP containing the header file, but they are all independent. Therefore, we do not recommend this method. We do not know how to use this variable, because only a group of variables with the same name and different scopes are created;
Here, by the way, how to declare all the global variables that CPP can share and declare them as extern in the header file:
Extern
Int g _;//
Note: Do not initialize the value!
Then initialize (once) in any CPP containing the header file:
Int
G _ = 0 ;//
Do not modify extern when initializing, because extern is also a declarative keyword;
Then, all CPP files containing the header file can access the same variable with the name G;
4. Only valid global functions in CPP:
Declare in CPP:
Static
Void
Func ();
The implementation of the function does not require static modification, so this function can only be used in this CPP, and it does not conflict with functions of the same name in other CPP; the problem is the same as that caused by not using static. Do not declare static global functions in the header file or non-static global functions in CPP, if you want to reuse this function in multiple CPP programs, you should mention its declaration to the header file. Otherwise, static modification is required for the CPP internal declaration. This is important 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.