Differences between static variables and instance variables

Source: Internet
Author: User

Syntax definition difference: the static keyword must be added before the static variable, but not before the instance variable.
Differences during program running: instance variables belong to the attributes of an object. You must create an instance object before the instance variables are
To use this instance variable. Static variables do not belong to a certain instance object, but belong to a class, so they are also called class variables.
If you want the program to load the class bytecode without creating any instance object, static variables are allocated space and static variables can be used.
In short, instance variables can be used only after an object is created. Static variables can be referenced directly by class names.
For example, for the following program, no matter how many instance objects are created, only one staticvar variable is assigned, and each creation
For an instance object, this staticvar will add 1; however, each time an instance object is created, an instancevar will be allocated, that is, possible
Multiple instancevar instances are allocated, and each instancevar value is added only once.
Public class varianttest {
Public static int staticvar = 0;
Public int instancevar = 0;
Public varianttest (){
Staticvar ++;
Instancevar ++;
System. Out. println ("staticvar =" + staticvar + ", instancevar =" + instancevar );
}
}
Note: In addition to clarifying the differences between the two, this answer also uses a specific application example to illustrate the differences between the two.
I have the ability to explain problems and design cases. I am more agile in thinking than ordinary programmers and can write!

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.