Differences between static methods, instance methods, and virtual Methods

Source: Internet
Author: User

Differences between static methods, instance methods, and virtual Methods
Basic knowledge for object-oriented languages, all types are from System. the Object type is derived. For this reason, each type has a set of basic methods, that is, from their parent class System. the Object inherits the ancient method. The definition of the Object is as follows. the basic methods defined by the Object basically contain all the CLR method types, Static methods (Static modification, belongs to class members), virtual methods (partial Ural modification, belongs to instance members), instance method (common method, belonging to instance members ). Some people may say that there are still abstract methods. In fact, the final compilation of abstract methods is also a virtual method. One of the most important features of CLR is type security. during runtime, CLR always knows the type of an Object. We can see that the Object has a GetType method, this method always knows the exact type of an object. Because GetType is a non-real-world example method, it ensures that the derived type cannot be overwritten, so one type cannot be disguised as another type, in fact, we can do this if we want to intentionally hide it (we can use the New keyword to overwrite the GetType method), but we generally do not recommend this. So how does the GetType method return the actual type of an object? This requires the introduction of a New concept, which is also a "type object". When we use the New keyword to create an object on the hosting stack, we roughly did a few things: class Program {static void Main (string [] args) {Person p = new Person ("Aseven"); Console. readKey () ;}} public class Person {private string _ name; private int _ age; public string Name {get {return _ name ;}set {_ name = value ;}} public virtual void Say () {Console. writeLine ("******");} public static Person Find (string name) {retur N new Person (name); // simulate database search} public int GetAge () {return _ age;} public Person () {} public Person (string name) {this. _ name = name ;}1. Calculation type and all base types (until System. object, although it does not define the instance field) All instance fields (Note: there are no static fields and methods) the number of bytes required, each object on the heap requires some additional members-type object pointers and synchronized index blocks. These members are used by CLR to manage objects and the size of the objects is also counted. 2. Allocate the object memory from the managed stack and initialize the field to zero (0 ). 3. initialize the "type Object Pointer" and "Synchronous Index block" of the object ". 4. Execute the instance constructor and pass in the real parameter specified in the new call ("Aseven" in the above example) to it "), most compilers automatically generate code to call the constructors of the base class. Instead, they call System. object constructor. After New is executed, a reference (or pointer) to the object in the heap is returned. For the previous example, the reference (Address) is saved in variable e, after this Person object is created, the memory structure is roughly as follows. You can see that the pointer of the type object points to the person type object. Conclusion: After an instance object is created, variable e stores a reference (pointer) of the person object in the managed heap ). The person object indicates that an instance field of the object is saved (including the type object pointer and Synchronous Index block), and the static field and method list are saved in the person type object, note that the method list contains static methods, instance methods, and virtual methods. The following describes how to call these three methods. Method call 1. Static Method: When a static method is called, the CLR locates the type object corresponding to the type that defines the static method (a bit around ). Find the corresponding record item in the method list of the type object, perform JIT compilation (if needed), and then call. 2. instance method: When a non-real-world sample method is called, the JIT compiler will find the type object corresponding to the type of the variable (p) that calls the call, if the method list of the type Object does not contain the called method, the JIT compiler will trace back the class hierarchy (always back to the Object ), and search for this method in each type of method set along the way, the reason for this backtracking is that each type object has a field referencing its accumulation, this information is not displayed on the way. 3. Virtual method: When a virtual method is called, some additional code is generated. The code is executed every time the method is called. The code first checks the variables that are called, then we will follow the address (that is, the pointer of the object stored in p) to the called object, and then the code will check the internal "type Object Pointer" member of the object, this member points to the type object of the object, and then the code searches for the method in the method set of the type object for JIT compilation (if needed), and calls the Code Compiled by JIT. If not, the method defined in the base class will be traced back. The following is an example: class Program {static void Main (string [] args) {Person p = new Person ("test1"); p = Person. find ("Aseven"); int Age = p. getAge (); p. say (); Console. readKey () ;}} public class Person {private string _ name; private int _ age; public string Name {get {return _ name ;}set {_ name = value ;}} public virtual void Say () {Console. writeLine ("*******");} public static Person Find (string name) {Return new Chinese (name); // simulate database search} public int GetAge () {return _ age;} public Person () {} public Person (string name) {this. _ name = name ;}} public class Chinese: Person {public Chinese (string name) {this. name = name;} public override void Say () {Console. writeLine ("Hello! ") ;}} Public class American: Person {public American (string name) {this. Name = name;} public override void Say () {Console. WriteLine (" Hello! ") ;}} 1. First, we define the Person object, Person p = new Person (); this code is basically similar to the above memory allocation after execution. 2. We call the static method of Person, p = Person. find ("Aseven"); according to the above definition, when a static method is called, the list of methods of the type object is directly searched and called, after the call, we can see that a Chinese object is directly returned in the Find method. This will create a chinese object in the hosting heap and store the address in the Variable P, in this case, P does not store the address of the Person object, but the address of the Chinese object (or an American object, if Find returns an American object ). 3. Then we call p. getAge () is a non-virtual instance method. When the CLR calls a non-virtual instance method, It will be based on the type of the caller (P) (Person) (Person type object) to find the GetAge method, if not found, back to the base class to find. This method is called directly because the method set of the Person object type contains this method. Store the returned results (0 here) to an Age variable on the thread stack. 4. Call P. the Say () method. The Say method is a virtual method. The CLR will send a pointer to a Chinese object based on the caller's (P) address) find the real object (chinese object) in the managed heap, find the real type object (Chinese object) based on the object in the managed heap, and traverse the method set to find the Say method, (If the Chinese class overwrites the Say method, this method is included in the method set of the Chinese class object. This memory allocation is roughly as follows: because the person object is no longer referenced by other objects, it will be the key object for next garbage collection. Test Demo public class A {public void MethodF () {Console. writeLine ("A.F");} public virtual void MethodG () {Console. writeLine (". G ") ;}} public class B: A {new public void MethodF () {Console. writeLine ("B. F ");} public override void MethodG () {Console. writeLine ("B .G") ;}} class Test {static void Main () {B B; B = new B (); A a = B;. methodF (); B. methodF ();. methodG (); B. methodG ();} output result:. F, B. f, B .G, B .G 1. First, MethodF is a non-real-world example method. At this time, we use. methodF (); because a is an instance of type A, the output is A.F. 2. Call B. methodF (). Because B is a B-type instance and B overwrites the MethodF method of a, the MethodF method is available in the method table of the B-type object, will be called directly, so the output is B. F 3. Because MethodG is a virtual method, we use. when calling MethodG, the system first finds the specific object in the managed heap based on the address (pointer) saved in a, and then finds the actual type object based on the specific object, here, a stores an instance of B, so the object type object is the type object of B, during the call, the method set in the type object of type B is directly searched for and called by the MethodG method. Therefore, B .G 4 is output for type B. mehtodG first finds the specific object in the managed heap based on the address (pointer) saved in B, and then finds the actual type object based on the specific object, here, B stores an instance of B, so the object type object is the type object of B, the method set in the type object of the B type object is directly searched for and called by the MethodG method. Therefore, B .G is output.

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.