The difference between static variables and instance variables in Java detailed introduction _java

Source: Internet
Author: User

Operation Effect:

Console effect:

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

Code section

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

/hello_test/src/com/b510/test/statictest.java

Copy Code code as follows:

/**
*
*/
Package com.b510.test;

/**
* The difference when the program is running: the instance variable belongs to the property of an object, and the instance object must be created,<br>
* The instance variables will be allocated space in order to use this instance variable. Static variable does not belong to a <br>
* An instance object, but belongs to the class, so also called the class variable, as long as the program loads the byte code of the class,<br>
* Without creating any instance objects, static variables are allocated space, and static variables can be used. <br>
* In summary, the instance variable must be created before it can be used by the object, and the static variable can be <br>
* Use the class name directly to refer to. For example, for the following program, no matter how many instance objects are created,<br>
* Always assign only one <code>staticInt</code> variable, and each instance object is created,<br>
* This <code>staticInt</code> will add 1; However, each instance object is created with a <code>random</code>,<br>
* It is possible to allocate multiple <code>random</code&gt, and each <code>random</code> value is only added 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 ();
}
}

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.