当前位置:网站首页>Life cycle of instance variables, static variables and local variables
Life cycle of instance variables, static variables and local variables
2022-07-04 01:45:00 【"Ice soul"】
List of articles
Preface
This article is from 《Java object-oriented programming : Sun Weiqin 》 Part of the third chapter , The purpose is to help you understand instance variables 、 Static variables 、 Concept of local variable life cycle
One 、 The life cycle of static variables and instance variables
There are two kinds of member variables of a class : One is being static Keyword modifies the variable , It's called class variable , perhaps Static variables , Has not been static Embellished , It's called Instance variables
The difference between static variables and instance variables is :
- There is only one static variable of class in memory ,Java The virtual machine allocates memory for static variables during class loading , Static variables are located in the method area , Shared by all instances of the class . Static variables can be accessed directly through the class name . The life cycle of a static variable depends on the life cycle of the class , When loading classes , Static variables are created and memory allocated , When unloading classes , Static variables are destroyed and memory is revoked .
- Each instance of a class has a corresponding instance variable . Every time an instance of a class is created ,Java The virtual machine allocates memory for instance variables once , Instance variables are in the heap . The life cycle of the instance variable depends on the life cycle of the instance , When creating an instance , Instance variables are created and memory allocated , When destroying instances , Instance variables are destroyed and memory is revoked .
following Counter Class has two member variables , among count1 Variables are instance variables , and count2 The variable is static :
public class Counter {
public int count1 = 0; //count1 Instance variables
public static int count2 = 0; //count2 Static variables
}
The following code creates two Counter example , Then modify their count1 and count2 Variable :
Counter counterA = new Counter();
Counter counterB = new Counter();
counterA.count1++;
counterA.count2++;
counterB.count1++;
counterB.count2++;
After executing the above code ,Java The runtime data area of the virtual machine is shown in the figure :
From the figure, we can understand the points mentioned before :
Static variables are located in the method area , Shared by all instances of the class .So static variables count2 There is only one in memory , perform counterA.count2++ or counterB.count2++ In fact, the manipulation is Counter The same static variable of class count2, The value is 2;Instance variables are in the heap .perform counterA.count1++ It's actually made up of CounterA Variable references Counter Example of count1 Variable , and counterB Refer to the count1 Variables are different , So their respective values are 1.
Combine the basic knowledge learned before , We know that static variables can be passed directly Class name . Variable Access... In this form :
counterA.count1++; // adopt counterA Reference variables to access count2 Variable
Counter.count2++; // adopt Counter Class name count2 Variable
about count1 Instance variables , Is it possible to Counter.count1( Class name access ) Visit ?
The answer is obviously no , We can see from the picture that , Instance variables always belong to a specific instance ,Java The virtual machine cannot know which instance variable the access is just by the class name .
Two 、 The life cycle of a local variable
What is a local variable ?
A local variable refers to a variable in Inside a method perhaps Method Variables declared in , The scope of the former is the whole method , The scope of the latter is this code block ( The code block is {} Code within )
I've got a general idea of local variable Concept , Let's look at its life cycle .
The life cycle of a local variable depends on when the method it belongs to is called and ends the call !
- When Java virtual machine ( More precisely , yes Java A thread in the virtual machine ) When a method is called , Memory will be allocated for local variables in this method .
- When Java The virtual machine ends this call , At the same time, it will end the life cycle of local variables in this method .
Use the following code example to further understand the life cycle of local variables :
public class Sample {
int var1 =1; //var1 Is instance variable
static int var2=2; //var2 It's a static variable
public int add(){
int var3 = var1 +var2; //var3 It's a local variable
return var3;
}
public int delete(){
int var4 = var1 - var2; //var4 It's a local variable
return var4;
}
public static void main(String[] args) {
new Sample().add();
}
}
The life cycle change process is as follows :
(1) load Sample class , Start amazing variables var2 Life cycle of ,var2 Located in method area .
(2) establish Sample example , Start instance variable var1 Life cycle of ,var1 Located in the heap area .
(3) call Sample Example of add() Method , Start local variable var3 Life cycle of ,var3 be located Java The stack area
(4) completion of enforcement Sample Example of add() Method , End local variable var3 Life cycle of , Return to main() Method .
(5) completion of enforcement Sample Class main() Method , end Sample Instance and its instance variables var1 Life cycle of , uninstall Sample class , End static variable var2 Life cycle of , therefore var4 Variable in Java The virtual machine has never been created during its operation .
Because local variables and member variables have completely different life cycles , When using local variables , Subject to the following restrictions :
1、 Local variables cannot be static、private、protected and public Wait for the modifier to decorate
Because the local variable itself is an access permission setting . Can only be called locally , That is to say, the life cycle of local variables is {} In addition to this method, the outside world has no way to access your variable , So there is no need to decorate with any modifiers , such as private、public、protected etc. . But you can add final, You can't add static Static keywords , because static Only member variables and member methods can be modified , Use... In local variables static modification , It cannot be called directly by classes , and static Keywords can be called directly with classes instead of directly passing through objects , So you can't add... Before the local variable static keyword
2、 Local variables cannot be accessed through class names or reference variables
Empathy , The life cycle of a local variable exists during the method being called , Scope is only within this method , Therefore, it cannot be directly accessed by the class name or reference variables .
Expanding knowledge
For local variables , If it's a basic type , Will store values directly on the stack ; If it's a reference type , such as String s = new String(“william”); Will store its objects in the heap , And the reference to this object ( The pointer ) Store on stack .
3、 ... and 、 summary
The life cycle of static variables depends on when classes are loaded and unloaded ;
The life cycle of instance variables depends on when instances are created and destroyed ;
The life cycle of a local variable depends on when the method it belongs to is called and ends the call .
Reference link :
https://blog.csdn.net/weixin_38756990/article/details/72857840
边栏推荐
- How programmers find girlfriends through blind dates
- Basic editing specifications and variables of shell script
- Pyinstaller packaging py script warning:lib not found and other related issues
- G3 boiler water treatment registration examination and G3 boiler water treatment theory examination in 2022
- What is the student party's Bluetooth headset recommendation? Student party easy to use Bluetooth headset recommended
- Neo4j learning notes
- 0 basic learning C language - nixie tube dynamic scanning display
- C import Xls data method summary IV (upload file de duplication and database data De duplication)
- Huawei rip and BFD linkage
- The force deduction method summarizes the single elements in the 540 ordered array
猜你喜欢

What are the advantages and disadvantages of data center agents?

Gee: create a new feature and set corresponding attributes

Lightweight Pyramid Networks for Image Deraining

Feign implements dynamic URL

Huawei cloud micro certification Huawei cloud computing service practice has been stable

IPv6 experiment

MySQL deadly serial question 2 -- are you familiar with MySQL index?
![Setting function of Jerry's watch management device [chapter]](/img/0b/8fab078e1046dbc22aa3327c49faa7.jpg)
Setting function of Jerry's watch management device [chapter]

Yyds dry goods inventory it's not easy to say I love you | use the minimum web API to upload files

Small program graduation project based on wechat examination small program graduation project opening report function reference
随机推荐
Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
What is the student party's Bluetooth headset recommendation? Student party easy to use Bluetooth headset recommended
LeetCode 168. Detailed explanation of Excel list name
MySQL deadly serial question 2 -- are you familiar with MySQL index?
A little understanding of GSLB (global server load balance) technology
Ka! Why does the seat belt suddenly fail to pull? After reading these pictures, I can't stop wearing them
51 single chip microcomputer timer 2 is used as serial port
How programmers find girlfriends through blind dates
A malware detection method for checking PLC system using satisfiability modulus theoretical model
All in one 1412: binary classification
Small program graduation project based on wechat examination small program graduation project opening report function reference
Applet graduation project is based on wechat classroom laboratory reservation applet graduation project opening report function reference
Flex flexible layout, box in the middle of the page
Feign implements dynamic URL
In the process of seeking human intelligent AI, meta bet on self supervised learning
Huawei cloud micro certification Huawei cloud computing service practice has been stable
Hash table, string hash (special KMP)
Flutter local database sqflite
Who moved my code!
Conditional statements of shell programming