In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to control objects and memory in java. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
1. Knowledge points of object and memory control
The initialization process of 1.java variables, including local variables, member variables (instance variables and class variables).
two。 In an inheritance relationship, there is a difference between the properties and methods that access the object when the compile-time type and the run-time type of the object reference variable are different.
3.final modifier properties.
Second, the division and initialization process of java variables
Java program variables can be divided into member variables and local variables, and member variables can be divided into instance variables (non-static variables) and class variables (static variables). Generally, the local variables we encounter will appear in the following situations:
(1) formal parameter: a local variable defined in a method signature, assigned by the caller and dies with the end of the method.
(2) Local variables within a method: the local variables defined in the method must be initialized (assigned initial values) displayed in the method, and die out with the completion of variable initialization and the end of the method.
(3) Local variables within the code block: local variables defined within the code block must be initialized (assigned initial values) displayed in the code block, take effect with the completion of initialization and die out with the end of the code block.
Package com.zlc.array;public class TestField {{String b; / / if not initialized, the compiler will report The local variable b may not have been initialized System.out.println (b);} public static void main (String [] args) {int a / / if not initialized, the compiler will report The local variable a may not have been initialized System.out.println (a);}}
The member variable modified with static is the class variable, which belongs to the class itself, and the member variable that is not modified with static is the instance variable, which belongs to the instance of this class. In the same JVM, each class can only correspond to one Class object, but each class can create multiple java objects. (that is, a class variable only needs a piece of memory space, and each time the class creates an instance, it needs to allocate a piece of space to the instance variable)
Initialization of instance variables: syntactically, a program can initialize instance variables in three places:
(1) specify the initial value when defining the instance variable.
(2) specify the initial value for the instance variable in the non-static block.
(3) specify the initial value for the instance variable in the constructor.
The initialization time of (1) and (2) is earlier than that of (3) in the constructor, and the initialization order of (1) and (2) is determined according to the order in which they are arranged in the source code.
Package com.zlc.array;public class TestField {public TestField (int age) {System.out.println ("initialization in constructor this.age =" + this.age); this.age = age;} {System.out.println ("initialization in non-static block"); age = 22 } / / initialize int age = 15; public static void main (String [] args) {TestField field = new TestField (24); System.out.println ("final age =" + field.age);}}
The running result is: initialization in a non-static block
Initialize this.age = 15 in the constructor
Final age = 24
If you know how to use javap, you can use javap-c XXXX (class file) to see how the modified java class is compiled.
The initial value is specified when the instance variable is defined. The statement that specifies the initial value for the instance variable in the initialization block is equal. After being compiled by the compiler, they are all mentioned in the constructor, the above-mentioned int age = 15. The following two steps are divided into:
1) when int age; creates a java object, the system allocates memory for the object according to this statement.
2) age = 15; this statement is extracted and executed in the constructor of the java class.
The initialization process of class variables: from a syntactic point of view, programs can initialize and assign class variables from two places.
(1) specify the initial value when defining a class variable.
(2) specify the initial value for the class variable in the static block.
The order of the two kinds of execution is the same as that in the source code. Let's give an example of a little pervert:
Package com.zlc.array; class TestStatic {/ / Class member DEMO TestStatic instance final static TestStatic DEMO = new TestStatic (15); / / Class member age static int age = 20; / / instance variable curAge int curAge; public TestStatic (int years) {/ / TODO Auto-generated constructor stub curAge = age-years }} public class Test {public static void main (String [] args) {System.out.println (TestStatic.DEMO.curAge); TestStatic staticDemo = new TestStatic (15); System.out.println (staticDemo.curAge);}}
The output result is printed on two lines, one is to print the instance variable of the TestStaticclass property DEMO, and the second is to output the instance property of TestStatic through the java object staticDemo, which can be inferred from the initialization process of the instance variable and class variable analyzed above:
1) in the first stage of initialization, the class variables DEMO and age are allocated memory space when the class is loaded. The default values of DEMO and age are null and 0, respectively.
2) in the second stage of initialization, the program assigns initial values to DEMO and age sequentially, TestStatic (15) needs to call TestStatic's constructor, at this time age = 0, so the print result is-15, and when staticDemo is initialized, age has been assigned equal to 20, so the output result is 5.
Third, the difference between inheriting member variables and inheriting member methods in inheritance relations.
When creating any java object, the program always calls the non-static block and parent constructor of the parent class first, and then the non-static block and constructor of the class. Calling the constructor of the parent class through the constructor of the subclass is generally divided into two cases, one is the implicit call, and the other is the constructor that invokes the parent class through super display.
The method of the subclass can call the instance variable of the parent class, because if the subclass inherits the parent class, it will get the member variable and method of the parent class, but the method of the parent class cannot access the instance variable of the subclass. because the parent class does not know which class it will inherit, what kind of member variables will be added to its subclass, of course, in some extreme examples, it is possible for the parent class to call the subclass variable. For example, if the subclass overrides the method of the parent class, it usually prints the default value, because the instance variable of the subclass has not been initialized at this time.
Package com.zlc.array;class Father {int age = 50; public Father () {/ / TODO Auto-generated constructor stub System.out.println (this.getClass ()); / / this.sonMethod (); cannot call info ();} public void info () {System.out.println (age) } public class Son extends Father {int age = 24; public Son (int age) {/ / TODO Auto-generated constructor stub this.age = age;} @ Override public void info () {/ / TODO Auto-generated method stub System.err.println (age) } public static void main (String [] args) {new Son (28);} / / method specific to the subclass public void sonMethod () {System.out.println ("Son method");}}
According to our normal inference, the constructor of the parent class is implicitly called through the subclass, and the info () method is called in the constructor of the parent class (note: I did not say that the parent class is called here). It is reasonable to output the age instance variable of the parent class, and the print result is expected to be 50, but the actual output is 0. Analyze the reason:
1) the memory allocation of the java object is not completed in the constructor, which only completes the process of initializing the assignment, that is, before calling the constructor of the parent class, jvm has classified the memory space for the Son object. This space stores two age attributes, one is the age of the subclass, and the other is the age of the parent class.
2) when calling new Son (28), the current this object represents the object of the subclass Son, we can print out the object .getClass () and get the result of class com.zlc.array.Son, but the current initialization process is carried out in the constructor of the parent class, and cannot be called through this.sonMethod (), this is because the compilation type of this is Father.
3) when the compile-time type and run-time type of a variable are different, when the instance variable of its reference object is accessed through the variable, the value of the instance variable is determined by the type that declares the variable, but when the instance method of the object it references is called through this variable, the behavior of the method is determined by the object it actually references, so the info method of the subclass is called here. So the age of the subclass is printed, and the default value of 0 is printed because age hasn't been initialized yet.
In popular terms, when the declared type is inconsistent with the real new type, the property used is the parent class and the method called is the subclass.
Through javap-c, we can more directly understand why there is a great difference between inheriting properties and methods. If we remove the info rewriting method of the subclass Son in the above example, the info method of the parent class will be called because the compilation of the info method of the parent class will be transferred to the subclass, while the member variables of the name will remain in the parent class. In this way, the subclass and the parent class have instance variables with the same name, and if the subclass overrides the method of the parent class with the same name, the method of the subclass completely overrides the method of the parent class (it is not clear why java is designed in this way). Variables with the same name can exist without overriding at the same time, and the subclass of the method with the same name completely overrides the method of the parent class with the same name.
In general, for a reference variable, when the instance variable of the object it references is accessed through that variable, the value of the instance variable depends on the type when the variable is declared, and when the method of the object it references is accessed through the variable, the method behavior depends on the type of object it actually references.
Finally, take a little case to review:
Package com.zlc.array;class Animal {int age; public Animal () {} public Animal (int age) {/ / TODO Auto-generated constructor stub this.age = age;} void run () {System.out.println ("animal run" + age) }} class Dog extends Animal {int age; String name; public Dog (int age,String name) {/ / TODO Auto-generated constructor stub this.age = age; this.name = name;} @ Override void run () {System.out.println ("dog run" + age) }} public class TestExtends {public static void main (String [] args) {Animal animal = new Animal (5); System.out.println (animal.age); animal.run (); Dog dog = new Dog (1, "xiaobai"); System.out.println (dog.age) Dog.run (); Animal animal2 = new Dog (11, "wangcai"); System.out.println (animal2.age); animal2.run (); Animal animal3; animal3 = dog; System.out.println (animal3.age) Animal3.run ();}}
Want to call the method of the parent class: can be called through super, but the super keyword does not refer to any object, it can not be used as a real reference variable, interested friends can study for themselves.
The above are instance variables and methods, class variables and class methods are much simpler, directly use the class name. The method is much more convenient and will not encounter so much trouble.
IV. The use of final modifiers (especially macro substitution)
Final can modify a variable, and a variable modified by final cannot be reassigned after it has been assigned an initial value.
Final can modify methods, and methods modified by final cannot be overridden.
Final can modify classes, and classes modified by final cannot derive subclasses.
The specified initial value that the variable modified by final must display:
For instance variables that are decorated by final, initial values can only be assigned in the following three specified locations.
(1) specify the initial value when defining the final instance variable.
(2) specify the initial value for the final instance variable in a non-static block.
(3) specify the initial value for the final instance variable in the constructor.
Will eventually be mentioned in the constructor for initialization.
For class variables specified with final: initial values can only be assigned in two specified places.
(1) specify the initial value when defining the final class variable.
(2) specify the initial value for the final class variable in the static block.
Also processed by the compiler, unlike instance variables, class variables refer to static blocks to assign initial values, while instance variables refer to constructors to complete.
Another feature of the class variable modified by final is "macro substitution". When the modified class variable satisfies the definition of the variable, the initial value is specified, and the initial value can be determined at the time of compilation (for example, 18, "aaaa", 16.78, etc.), then the final modified class variable is no longer a variable, the system will be treated as a "macro variable" (that is, we often call constant) If the initial value can be determined at compile time, it will not be mentioned for initialization in the static block, and the initial value will directly replace the final variable in the class definition. Let's take that age minus year as an example:
Package com.zlc.array; class TestStatic {/ / Class member DEMO TestStatic instance final static TestStatic DEMO = new TestStatic (15); / / Class member age final static int age = 20; / / instance variable curAge int curAge; public TestStatic (int years) {/ / TODO Auto-generated constructor stub curAge = age-years }} public class Test {public static void main (String [] args) {System.out.println (TestStatic.DEMO.curAge); TestStatic static1 = new TestStatic (15); System.out.println (static1.curAge);}}
At this time, the age is modified by final, so at compile time, all age in the parent class becomes 20, not a variable, so that the output meets our expectations.
Especially when comparing strings, it can show
Package com.zlc.array;public class TestString {static String static_name1 = "java"; static String static_name2 = "me"; static String statci_name3 = static_name1+static_name2; final static String final_static_name1 = "java"; final static String final_static_name2 = "me" / / add final or not, the first two can be replaced by macros final static String final_statci_name3 = final_static_name1+final_static_name2; public static void main (String [] args) {String name1 = "java"; String name2 = "me"; String name3 = name1+name2 / / (1) System.out.println (name3 = = "javame"); / / (2) System.out.println (TestString.statci_name3 = = "javame"); / / (3) System.out.println (TestString.final_statci_name3 = = "javame");}}
There is nothing to say about decorating methods and classes with final, but one cannot be overridden by a subclass (like private), and a subclass cannot be derived.
When using final to modify local variables, Java requires local variables accessed by internal classes to be modified with final for a reason. For ordinary local variables, its scope stays in the method, and when the method ends, the local variable disappears, but the inner class may produce an implicit "closure", which makes the local variable continue to exist away from its method.
Sometimes when you new a thread in a method and then call the method's local variable, you need to declare the change variable as final-decorated.
On how to control objects and memory in java to share here, I hope the above content can be of some help to you, you can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.