In iOS, the view controller and view class have the concept of life cycle, It was very complicated to set the auto layout. So I was wondering what about Android. It was known that Android also has a life cycle in Activity, For the first time today, I learned that language specifications also have a life cycle.
Maybe I wasn't even aware of Objective-C or Swift, There may have been an object life cycle.
Therefore, I will summarize the life cycle in the mJava language.
There are roughly three types of object life cycles.
--Local variables --Instance variables --Class variables
Local variables are variables that can only be used within a block of processing.
LocalVar.java
int sampleMethod() {
int count = 0; //Local variables
return count;
}
It is generated at the place where the variable is declared, and is destroyed when the block processing is completed.
Instance variables are variables that are declared as fields in a class. The life cycle of an instance variable is the same as the life cycle of an instance of a class, Created when the parent object is created and destroyed when the parent object is garbage collected. Garbage collection is a mechanism that releases unnecessary areas of the memory area allocated by the program.
A class variable is a variable that is declared as a static field in a class. Has the longest life cycle. It is created when the class is loaded and destroyed when it is destroyed.
LifeCycleSample.java
public class LifeCycleSample {
public static int classVariable = 1; //Class variables
public int instanceVarialbe = 1; //Instance variables
public void sampleMethod() {
int localVariable = 1; //Local variables
return localVariable;
}
}
There are roughly two patterns of good practices for declaring variable objects.
I myself have tried to minimize the scope by declaring variables where necessary in the field so far. If you hold it for too long, the variable will be called from another place at an unintended timing and the state will change (laughs). It is clear that unintended programs can cause bugs and should be avoided as much as possible.
So, for me, I think it's easy to do a pattern that shortens the life cycle of 1.
Recommended Posts