Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use static fields and static methods in Java

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the static fields and static methods in Java how to use, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

Let's take a look at the following code:

Public class Main {public static void main (String [] args) {System.out.println ("Hello, WOrld!");}}

Our main method is marked with the static modifier, so what does the static modifier mean?

I. static variables

If a field is defined as static, there is only one such field per class.

Let's first take a look at the classes that do not have static traversal:

Class Student {int stuId; String name; String school = "HY No.1 High School";}

Assuming that there are 1500 students in high school, all instance data members of the above code now get memory each time an object is created.

All students have their own unique stuId and names, and these instance data members are correct in this case, after all, are unique.

However, the "school" here is a common property of all objects. If it is not declared as a static variable, it will take up more than one memory. But if we make it static, this field will only get memory once.

Static variable declaration class Student {int stuId; / / instance variable String name; static String school = "HY No.1 High School"; / / static variable}

If you declare any variable as static, it is called a static variable.

Static variables can be used to refer to the common properties of all objects (not unique to each object), such as the company name of the employee, the name of the student's college, and so on.

Static variables get memory in the class area only once when the class is loaded.

Static variable test

Code testing:

Package com.yuzhou1su.RelearnJava;class Student {int stuId; String name; static String school = "HY No.1 High School"; Student (int id, String n) {stuId = id; name = n;} void display () {System.out.println ("Student id:" + stuId + ", Name:" + name + "is from" + school) }} public class TestVariable {public static void main (String [] args) {/ / TODO Auto-generated method stub Student S1 = new Student (001, "Karsa"); Student S2 = new Student (002, "Ellen"); s1.display (); s2.display ();}}

Execution result:

Student id:1, Name:Karsa is from HY No.1 High School

Student id:2, Name:Ellen is from HY No.1 High School

Static variables only get memory once, and if any object changes the value of the static variable, it retains its value.

Look at the following code:

Package com.yuzhou1su.RelearnJava;public class StaticVariableCount {static int count = 0; StaticVariableCount () {count++; System.out.println (count);} public static void main (String [] args) {/ / TODO Auto-generated method stub StaticVariableCount svc1 = new StaticVariableCount (); StaticVariableCount svc2 = new StaticVariableCount (); StaticVariableCount svc3 = new StaticVariableCount ();}}

Test results:

one

two

three

Second, static method

A static method in Java is a method that belongs to a class but is not considered an instance of that class; on the contrary, static methods in Java can be easily created and implemented without any instance calls. Static methods can access any data member in the class, perform any operation on the data member, or take any numeric value as input, although the member variable to be accessed should have a variable scope in the class, and the method can only be static.

Public static void syntax_ex (String_name) {Body of the program for execution.}

Public . The access modifier for this class is public.

Static . The scope of the method is static, which means that all member variables and return types are static.

Void . This keyword in the syntax flow indicates that no return types are processed in the current method.

Syntax_ex .

Body . It includes the entire core logic or business logic (if needed in static mode).

If you use static keywords on any method, it is called static method

Static method:

Static methods belong to the class, not the objects that belong to the class.

Static methods can be called without creating an instance of a class.

Static methods can access static data members and change their values.

Static method testing

What if we want to change the operation of learning names? You can declare a static method.

Package com.yuzhou1su.RelearnJava;class Student {int stuId; String name; static String school = "HY No.1 High School"; static void changeSchool () {school = "HY No.5 High School";} Student (int id, String n) {stuId = id; name = n } void display () {System.out.println ("Student id:" + stuId + ", Name:" + name + "is from" + school);}} public class TestVariable {public static void main (String [] args) {/ / TODO Auto-generated method stub Student.changeSchool (); Student S1 = new Student (001, "Karsa"); Student S2 = new Student (002, "Ellen") S1.display (); s2.display ();}}

Test results:

Student id:1, Name:Karsa is from HY No.5 High School

Student id:2, Name:Ellen is from HY No.5 High School

How static methods work

Static methods and instance methods are two methods in Java, which cause some confusion among programmers, but this is just a misunderstanding. There is a big difference between static methods and instance methods. Let's see how static methods work in Java. A static method in Java is a method that resides in a class and can be accessed even if an object is not created or instantiated. You can access any instance of the class by adding the name of the method after the name of the class and passing parameters.

It can be represented as ClassName.methodName (arguments). In addition, the composition of these methods has the goal that the method should be shareable with all member variables in the class and everyone's object, whose scope is defined by the modifier static. These methods do not have any overloading capabilities; instead, they can be overloaded at compile time using the compiler's static binding, whenever the programmer needs to share a common code snippet among all instances, objects, or member variables of the class. the static method becomes a savior because it creates a shared stipulation for all members, objects, and variables by creating a common static scope.

All static fields of a class can be accessed using static fields as part of a class's static methods. In addition, static methods are also related to memory allocation and can be supported. It stores some of the static method fields and variables in memory with some permanently generated heap for associating values. Memory allocation does not support the creation of an object as a static method heap, or the method itself does not support instantiation. But the next question is how static methods work as part of a class by sharing and creating the scope of all members.

Why the Java Main method is static

This is because the object does not need to call static methods. If it is a non-static method, JVM first creates an object and then calls the main () method, which leads to additional memory allocation problems.

The main method does not operate on any objects; in fact, there are no objects when the program is started. The static main method executes and constructs the objects needed by the program.

Static constant

Static variables are rarely used, but static constants are commonly used. For example, define a static constant in the Math class:

Public class Math {public static final double PI = 3.14159265358979;}

Then in the program, you can use Math.PI to access the constant.

IV. Summary

Why do you need static variables in Java?

Answer: whenever we want to have a common property for all objects of a class, we use a class-level variable, a static variable.

This variable is loaded only once in memory when the class is loaded. Because it is not defined by object in Java, memory can be saved.

Why is it not a good habit to create static variables with Java?

Answer: static variables are common to all objects of the class. If you create a new object, you do not need to test the value of the static variable. Any code that uses static variables can be in any state. It can be within a new object or at the class level. Therefore, the scope of static variables is open in the Java class.

If we want tighter control over the scope, the variable should be created at the object creation level.

Similarly, it is not a good habit to define static variables because they violate the principles of object-oriented programming.

What is the purpose of static methods in Java?

Answer: Java provides the ability of static methods to create behaviors at the class level. Static methods are common to all objects of the class. We do not need to create any objects of the class to call static methods. Therefore, it provides the convenience of not creating an object to call it.

Static methods can also access and modify static data members. This also helps to maintain behavior and state at the class level.

Why mark the main method as a static method in Java?

Answer: the main method in Java is marked as static, so JVM can call it to start the program. If the main method is not static, which constructor will the Java process call?

Therefore, it is a well-known convention to mark primary methods as static in Java. However, if we remove static, there will be ambiguity. The Java process may not know which class's method to call to start the program.

Therefore, this convention helps the Java process identify the startup code of the program in the class that is passed as a parameter to the Java process.

Under what circumstances do we use static blocks?

Answer: sometimes there is a class with static member variables. These variables require some complex initialization. At this point, static blocks can be used as a tool for initializing complex static member variables. Static blocks are executed even before main is executed. Sometimes, we can replace static blocks with static class methods.

Can the program be executed without defining the main () method?

Answer: no, starting with Java 7, you need the main () method to execute the program. In earlier versions of Java, there was a workaround for using static block execution. But now the gap has narrowed.

What happens when the static modifier is not mentioned in the signature of the main method?

Answer: according to the Java specification, main methods must be marked as static. It only requires the parameters of a string array.

Programs can be compiled using non-static methods. But a NoSuchMethodError is given at execution time.

What is the difference between static methods and instance methods in Java?

Answer: in general, you need to define behavior for classes that do not depend on object member variables. This behavior is captured by static methods. If there is a behavior that depends on object member variables, we will not mark it as static, but keep it as an instance method.

To call as a static method, we do not need to create an object. We only call it by the name of the class. But to call the instance method, we need to create / get an object first.

Instance member variables cannot be accessed through static methods. However, instance methods can call instance variables and static variables.

Thank you for reading this article carefully. I hope the article "how to use static fields and static methods in Java" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report