9.Java static keywords and Java static variables and static methods

Source: Internet
Author: User
Tags pow

The static modifier can be used with variables and methods, which means "static".

Static variables and static methods can be accessed through the class name and do not need to create a class object to access the static members of the class, so the static decorated members are also known as class variables and class methods. Static variables are different from instance variables, and instance variables are always accessed through objects because their values differ between objects and objects.

Take a look at the following example:

  1. Public class Demo {
  2. static int i = ten;
  3. Int J;
  4. Demo() {
  5. this. J = ;
  6. }
  7. public static void main(String[] args) {
  8. System. Out. println("class variable i=" + Demo. I);
  9. demo obj = New demo();
  10. System. Out. println("instance variable j=" + obj. J);
  11. }
  12. }

Operation Result:
Class variable i=10
Instance variable j=20

Static memory allocation

Static variables belong to a class and do not belong to any independent object, so you can access static variables without creating an instance of the class. The result is that the compiler creates only one copy of the static variable for the entire class, that is, allocating only one memory space, although there are multiple instances, the instances share the memory. Instance variables are different, each time an object is created, the memory space is allocated once, the memory of different variables is independent from each other, and changing the instance variable of a object does not affect the B object.

Take a look at the following code:

  1. Public class Demo {
  2. static int i;
  3. Int J;
  4. public static void main(String[] args) {
  5. Demo obj1 = New demo();
  6. Obj1. I = ten;
  7. Obj1. J = ;
  8. Demo obj2 = New demo();
  9. System. Out. println("obj1.i=" + obj1. I + ", obj1.j=" + obj1. J);
  10. System. Out. println("obj2.i=" + obj2. I + ", obj2.j=" + obj2. J);
  11. }
  12. }

Operation Result:
obj1.i=10, obj1.j=20
obj2.i=10, obj2.j=0

Note: Although static variables can also be accessed through objects, they are not advocated and the compiler generates warnings.

In the above code, I is a static variable, change the value of I by OBJ1, will affect the obj2;j is an instance variable, by obj1 change the value of J, will not affect the obj2. This is because obj1.i and obj2.i point to the same memory space, and OBJ1.J and OBJ2.J point to different memory spaces, see:

Figure 1 Static variable memory allocation

Note: Static variables are initialized when the class is loaded. That is, whenever a class is loaded, it will be initialized whether or not you use the static variable.

Summary: Class variables is modified with the keyword static, when the class is loaded, allocates the memory of the class variable, and later generates the class's instance object, the memory (class variable) will be shared, and any modification of the class variable by any object will affect other objects. There are two external access methods: Access by object or by class name.

Static methods

A static method is a method that cannot be manipulated against an object. For example, the POW () method of the Math class is a static method with the syntax of Math.pow (x, a), which computes the power of a in X, without creating any Math objects.

Because static methods cannot manipulate objects, instance variables cannot be accessed in static methods, only static variables of their own classes can be accessed.

Static methods can be used in the following situations:

    • A method does not require access to the object state, and its required parameters are provided by explicit arguments (for example, Math.pow ()).
    • A method only needs to access the static variables of the class.

The reader must note that main () is also a static method and does not operate on any object. In fact, there are no objects at the start of the program, and the main () method is the entry for the program, which is executed and the object required by the program is created.

A summary of static variables and static methods:

    • A static method of a class can only access static variables;
    • A static method of a class is not able to invoke a non-static method directly;
    • Static variables and static methods can also be accessed through objects, but not recommended, as access control permissions allow;
    • The current object does not exist in the static method and therefore cannot be used, nor can the super be used, of course;
    • Static methods cannot be overridden by non-static methods;
    • The construction method does not allow the declaration to be static;
    • Local variables cannot use static adornments.

Examples of static methods:

  1. Public class Demo {
  2. static int sum(int x, int y){
  3. return x + y;
  4. }
  5. public static void main(String[] args) {
  6. int sum = Demo. Sum(ten, ten);
  7. System. Out. println("10+10=" + sum);
  8. }
  9. }

Operation Result:

The static method does not require any instances of the class it belongs to be called, so there is no this value and the instance variable cannot be accessed, otherwise it will cause a compilation error.

Note: Instance variables can only be accessed through objects and cannot be accessed through a class.

Static initializers (static blocks)

A block is a piece of code surrounded by curly braces. Static Initializer is a static block that exists in the class, outside of the method. Static initializers are only executed once when the class is loaded (the first time the class is used) and are often used to initialize static variables.

Example code:

  1. Public class Demo {
  2. public static int i;
  3. static{
  4. I = ten;
  5. System. Out. println("Now in Static block.") );
  6. }
  7. public void Test() {
  8. System. Out. println("Test method:i=" + i);
  9. }
  10. public static void main(String[] args) {
  11. System. Out. println("demo.i=" + Demo. I);
  12. New Demo(). Test();
  13. }
  14. }

The operating result is:
Now in static block.
Test method:i=10

Static Import

Static import is a new feature of Java 5 that imports static variables and static methods for a class.

In general, we import classes that write:

    1. Import PackageName. ClassName; //Import a specific class


    1. Import PackageName. *; //Import all classes in a package

Static imports can be written like this:

    1. Import static PackageName. ClassName. Methonname; //Import a specific static method


    1. Import static PackageName. ClassName. *; //Import all static members in a class

After importing, you can call a static method directly in the current class using the method name without having to use classname.methodname to access it.

For static variables and static methods that are used frequently, you can import them statically. The advantage of a static import is that it simplifies some operations, such as the output statement System.out.println (); The out in is the static variable of the System class, which can be java.lang.system.* by the import static; Import it, and the next time you call Out.println ().

Take a look at the following code:

  1. Import static Java. lang. System. *;
  2. Import static Java. lang. Math. Random;
  3. Public class Demo {
  4. public static void main(String[] args) {
  5. Out. println("a random number generated:" + Random());
  6. }
  7. }

Operation Result:
A random number generated: 0.05800891549018705

9.Java static keywords and Java static variables and static methods

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.