In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how to master the static keyword". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
"Brother, a week has passed, and you haven't updated your younger sister's Java. You've been lazy!" The third sister asked me with concern.
"update it today." I said to the third sister with a smile, "you can't be left behind in your study. Today let's learn the keyword static in Java."
"static is a difficult keyword in Java, and it is one of the most popular knowledge points asked by interviewers in major companies." I took a sip of coffee and went on.
"since it's the focus of the interview, I have to study hard." The third sister said hurriedly.
"the role of the static keyword can be described in one sentence:'it is convenient to call without creating an object, including variables and methods. 'that is, as long as the class is loaded, it can be accessed through the class name." I held my heavy glasses and continued, "static can be used to modify the member variables of a class, as well as member methods. Let's look at it one by one."
01. Static variable
"if you use the static keyword when declaring a variable, the variable is called a static variable. Static variables get memory space only once when the class is loaded, which makes static variables save memory space." The heating in the house is a little adequate, I ran to open a little window and continued.
"to consider such a Student class." As soon as the words fell, I crackled on the keyboard.
Public class Student {String name; int age; String school = "Zhengzhou University";}
After typing this code, I said to my third sister, "if Zhengzhou University admits 10, 000 freshmen, then when creating 10, 000 Student objects, all fields (name, age and school) will get a piece of memory. Students' names and ages are different, but they all belong to Zhengzhou University. If each object is created, the school field takes up a piece of memory, right? third sister."
"therefore, it is best to set the school field to static so that it takes up only one piece of memory instead of 10, 000."
There was another crackle of keyboards in the quiet house.
Public class Student {String name; int age; static String school = "Zhengzhou University"; public Student (String name, int age) {this.name = name; this.age = age;} public static void main (String [] args) {Student S1 = new Student (Silent King II, 18); Student S2 = new Student (Silent King III, 16);}}
"look, third sister. S1 and S2 are stored in the stack, Silent King 2 + 18 and Silent King 3 + 16 in the heap area, and the static variable school is stored in the static area."
"wait, brother, stack, heap, static zone?" The face of the third sister was covered with doubts.
"Oh, don't worry, third sister, you'll understand all the pictures." With that, I opened the website draw.io and drew the picture carefully.
"now, is it clear at once?" Looking at this beautiful hand drawing, I feel a little happy.
"Wow, brother, it's amazing!" The third sister did not forget to kiss ass and gave me a big compliment.
"all right, third sister, let's take a look at the following code."
Public class Counter {int count = 0; Counter () {count++; System.out.println (count);} public static void main (String args []) {Counter C1 = new Counter (); Counter c2 = new Counter (); Counter c3 = new Counter ();}}
"We create a member variable count and let it increment itself in the constructor. Because the member variable acquires memory when the object is created, each object has a copy of count, and the value of count does not increase with the number of objects."
I was talking eloquently, and the third sister didn't seem to understand.
"it doesn't matter, third sister, you can guess blindly first. What is the output of this code?"
"according to your logic, should you output three 1s? is that right?" The third sister blinked and answered a little less confidently.
"Oh, not bad."
I clicked the run button in IDEA and the program started to run.
one hundred and eleven
"every time you create a Counter object, the value of count increases from 0 to 1. Third sister, think about it. What if count is static?"
"I don't know."
"well, take a look at the following code."
Public class StaticCounter {static int count = 0; StaticCounter () {count++; System.out.println (count);} public static void main (String args []) {StaticCounter C1 = new StaticCounter (); StaticCounter c2 = new StaticCounter (); StaticCounter c3 = new StaticCounter ();}}
"Let's take a look at the output."
one hundred and twenty three
"A simple explanation, ha, because static variables only get memory space once, so any changes to it will be retained, so every time an object is created, the value of count will be increased by 1, so the end result is 3, see? third sister. This is the difference between static variables and member variables."
"in addition, it is important to note that because static variables belong to a class, do not access them through object references, but directly through the class name, otherwise the compiler will issue a warning."
02. Static method
"after talking about static variables, let's talk about static methods." With that, I was going to order a Huazi to smoke. The third sister stopped me. She pointed to the "smoking is harmful to health" on the cigarette case. I laughed.
"all right." I had to take a sip of coffee and continue, "if the static keyword is added to the method, then it is a static method."
"static methods have the following characteristics."
Static methods belong to this class, not the objects of this class.
You do not need to create an object of this class when calling a static method
Static methods can access static variables.
"come on, continue with the code."
Public class StaticMethodStudent {String name; int age; static String school = "Zhengzhou University"; public StaticMethodStudent (String name, int age) {this.name = name; this.age = age;} static void change () {school = "Henan University";} void out () {System.out.println (name + "" + age + "" + school);} public static void main (String [] args) {StaticMethodStudent.change (); StaticMethodStudent S1 = new StaticMethodStudent (Silent King II, 18) StaticMethodStudent S2 = new StaticMethodStudent (Silent King 3, 16); s1.out (); s2.out ();}}
"listen carefully, third sister. The change () method is a static method, so it can directly access the static variable school and change its value to Henan University; and it can call the change () method directly through the class name, like StaticMethodStudent.change ()."
"Let's take a look at the output of the program."
Silent Wang II 18 Henan University Silent Wang San 16 Henan University
"it should be noted that static methods cannot access non-static variables and call non-static methods. You see, third sister, if I change the code a little, the compiler will report an error."
"first, the compiler does not allow access to non-static variables in static methods."
"then access non-static methods in static methods, which are also not allowed by the compiler."
"is it clear about the use of static methods, third sister?"
Looking at the third sister nodding, I smiled with relief.
"Brother, I have a question: why is the main method static?" Unexpectedly, the third sister's ability to connect knowledge points is still good.
"if the main method is not static, it means that the Java virtual machine needs to create an object before it can call the main method when it executes, and the main method, as the entry of the program, is redundant to create an additional object." My thoughtless answer made the third sister feel very admired.
"almost all methods of the java.lang.Math class are static and can be called directly through the class name without creating an object of the class."
03. Static code block
"third sister, stand up and exercise. My neck is a little stiff."
We walked to the window and saw snowflakes falling from the sky. The third sister and I were so happy that we couldn't wait to open the window and reach out to touch the temperature of the snowflakes, which was so fleeting and cold that it was really comfortable.
"the scenery of the north, thousands of miles of ice, thousands of miles of snow. Look inside and outside the Great Wall, only reckless; up and down the river, suddenly lost the surging. The mountain dance silver snake, the original Chi wax figure, want to compete with the heavenly duke. Must sunny day, see red wrapped, particularly enchanting." The third sister could not help reciting "Spring Snow in Qinyuan".
It is really gratifying, this is the first snow in Luoyang in 2020, and it is really happy.
A moment later.
"in addition to static variables and static methods, the static keyword plays an important role." I said to the third sister happily, "the code enclosed by a static keyword and curly braces is called a static code block."
"like the following code."
Public class StaticBlock {static {System.out.println ("static code block");} public static void main (String [] args) {System.out.println ("main method");}}
"static code blocks are usually used to initialize static variables, which take precedence over the main () method."
"Let's take a look at the output of the program."
Static code block main method
"Brother, since the static code block executes before the main () method, can the Java class without the main () method execute successfully?" I admire the brain circuit of the third sister more and more.
"Java 1.6 is OK, but Java 7 cannot be executed at first." I answered with confidence.
Public class StaticBlockNoMain {static {System.out.println ("static code block, no main");}}
"when java StaticBlockNoMain is executed on the command line, an error for NoClassDefFoundError is thrown."
"third sister, let's take a look at the following example."
Public class StaticBlockDemo {public static Listwrites = new ArrayList (); static {writes.add (Silent King II); writes.add (Silent King III); writes.add (Silent King IV); System.out.println (first Block);} static {writes.add (Silent King five); writes.add (Silent King six); System.out.println (second Block);}}
"writes is a static ArrayList, so it is unlikely to complete initialization at declaration time, so initialization needs to be done in a static code block."
"static code blocks are really useful in the initial collection. In actual project development, static code blocks are usually used to load configuration files into memory."
04. Static inner class
"third sister, in addition to the above, static also has a less commonly used function-static inner classes."
"Java allows us to declare an inner class in a class, which provides a convincing way to use variables in only one place, making the code more organized and readable."
"there are four common inner classes, namely, member inner class, local inner class, anonymous inner class and static inner class. Due to the limited space, the first three are not within the scope of our discussion this time, and we will have the opportunity to elaborate on them later."
"take a look at the following example." The third sister was a little distracted. I knocked her on the head and went on.
Public class Singleton {private Singleton () {} private static class SingletonHolder {public static final Singleton instance = new Singleton ();} public static Singleton getInstance () {return SingletonHolder.instance;}}
"third sister, cheer up, it will be over soon."
"Oh, this code looks very chic, brother."
"Yes, third sister, this code will be seen later when you create a singleton."
"instance is not initialized the first time the Singleton class is loaded, and the Java virtual machine starts loading SingletonHolder and initializing instance only when the getInstance () method is called for the first time, which ensures not only thread safety but also the uniqueness of the Singleton class. However, a more elegant way to create a singleton is to use enumerations, which I'll talk to you later."
"it is important to note that, first, static inner classes cannot access all member variables of external classes; second, static inner classes can access all static variables of external classes, including private static variables. Third, external classes cannot be declared as static."
"third sister, you see, after adding static to the Singleton class, the compiler prompted an error."
This is the end of the content of "how to master static keywords". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.