The differences between static and instance variables in Java are described in detail

  • 2020-04-01 01:49:13
  • OfStack

Operation effect:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050216371533.png "width = 703 height = 292 >

Console effect:

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201305/2013050216371534.png "width = 584 height = 178 >

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

Code section

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

/ hello_test/SRC/com/b510 / test/StaticTest Java



 package com.b510.test;

 /**
  *  The difference while the program is running: the instance variable belongs to an object's property, the instance object must be created, <br>
  *  The instance variable is allocated space so that it can be used. Static variables don't belong to something <br>
  *  So it's called a class variable, as long as the program loads the bytecode of the class, <br>
  *  Without creating any instance objects, static variables are allocated space, and static variables can be used. <br>
  *  In short, an instance variable must be created before it can be used with the object, and a static variable can <br>
  *  Use the class name directly. For example, for the following program, no matter how many instance objects are created, <br>
  *  There's only one assigned forever <code>staticInt</code> Variables, and for every instance object created, <br>
  *  this <code>staticInt</code> Will add 1 ; However, for every instance object created, one is assigned <code>random</code> . <br>
  *  That is, more than one may be allocated <code>random</code> And each <code>random</code> I'm just adding the values 1 Times. <br>
  * 
  * @author <a href="mailto:hongtenzone@foxmail.com">hongten</a>
  * @date 2013-3-2
  */
 public class StaticTest {

     private static int staticInt = 2;
     private int random = 2;

     public StaticTest() {
         staticInt++;
         random++;
         System.out.println("staticInt = "+staticInt+"  random = "+random);
     }

     public static void main(String[] args) {
         StaticTest test = new StaticTest();
         StaticTest test2 = new StaticTest();
     }
 }


Related articles: