Something About "static"

xiaoxiao2021-03-06  79

Static members (including static methods) are Class, not an instance of this class. For example, the integer class, I may need to output a size of an instance of an integer class, and it is possible to obtain the maximum value of the integer class. Where "integer class's maximum" is not an instance of a particular integer class, but is an integer class, so that the method of obtaining the "maximum value" must be static. For example: class integer {int value; public static int maximun () {...} // Get the maximum value of the integer class public void print () {...} // Print the size of the integer value} is because MaxImun Don't belong to an instance of a specific integer class, so you can't write this: Integer i = new integer (); system.console.writeline (i.maximun ()); It is also because the static method belongs to the entire class, so in a static method, you can only use a static field (which is also a whole class), and cannot use the field that relies on a particular instance (that is, no Static fields), because the static method does not depend on a specific instance. Another example: For example, "people" class, everyone has name, age, gender, and height, these attributes should be non-static, because everyone's attributes are different; but people are biology Which of the top of which is the same, this property is the entire humanity, so it should be static - it does not rely on a particular person, there will be no one "vertebrate mammalian dragonfly" And someone is "the objection" :) method takes up more memory, and it is not a relationship with static. Because the field is used to store information for each instance object, the field will hold memory, and because the status of each instance object is inconsistent (at least if they are consistent), the field of each instance object will be There is a copy of the memory, because you can use them to distinguish which object you are doing now. But the method is different, no matter how many instance objects, the code of its method is the same, so as long as there is a code. Therefore, both static or non-static methods, there is only one code, that is, only one memory space. The same code, why is it running different? This relies on the data used by the method. There are two main sources of data, one is to pass the parameters of the method, the other is the value of the member variable of the class ... Static method, only access to static members. You cannot access instance members. For example, there is a field username in a class user if you use a static field (static string), if you want to have two USERNAEM different User instances, what should I do? So don't necessarily have to declare a static, or instance to analyze a textbook code according to the actual situation: use system; using system.collection;

转载请注明原文地址:https://www.9cbs.com/read-107867.html

New Post(0)