What is the difference between static variables and instance variables?

Source: Internet
Author: User

(1) InSyntax definitionDifferences:

The static keyword must be added before the static variable, but not before the instance variable.

(2) InProgramRunTime Difference:

The instance variable belongs to the attribute of an object. You must create an instance object. Only instance variables in the instance can be allocated space 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. As long as the program loads the class bytecode, no instance object needs to be created, 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.

(3) For example, for the following program:

No matter how many instance objects are created, only one staticvar variable is always assigned. Each time an instance object is created, 1 is added to this staticvar variable;

However, each time an instance object is created, an instancevar will be assigned, that is, multiple instancevar may be allocated, and the value of each instancevar is only added once.

Public class varianttest {public static int staticvar = 0; Public int instancevar = 0; Public varianttest () {staticvar ++; instancevar ++; system. out. println ("staticvar =" + staticvar + ", instancevar =" + instancevar );}}
 

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.