Interview Question 7: What is the difference between a static variable and an instance variable? __ Face Test

Source: Internet
Author: User

The difference between a static variable and an instance variable.

/*

The difference in syntax definition: the static key is added before the statically variable, and the instance variable is not previously added.
* The difference when the program is running: the instance variable belongs to the property of an object, and an instance object must be created in which the instance variable is allocated space.
* To use this instance variable. A static variable is not part of an instance object, but belongs to a class, so it is also called a class variable, as long as the program loads the class
* Byte code, without creating any instance objects, static variables will be allocated space, static variables can be used. In summary, instance variables must be
* The object can be used only after it is created, and static variables can be referenced directly using the class name.
* For example, for the following program, no matter how many instance objects are created, only one staticvar variable is ever assigned, and each
* Instance object, this staticvar will add 1; However, each instance object is created, and a instancevar is allocated, which may
* Assign multiple Instancevar, and each Instancevar value is only added 1 times.
*/

public class Test11 {public
	static int staticvar = 0;
	public int instancevar = 0;

	Public Test11 () {
		staticvar++;
		instancevar++;
		System.out.println ("staticvar=" + Staticvar + ", instancevar="
				+ Instancevar);
	}

	public static void Main (string[] args) {
//		Test11.staticvar = 1;
		
		Test11 test = new Test11 (); 1  1
		Test11 test1 = new Test11 ();//2  1
		Test11 test2 = new Test11 ();//3  1
		
//		test.staticvar=0;		test.instancevar=0
	}
}


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.