The difference between a "Java" class variable and an instance variable

Source: Internet
Author: User

The difference between class and instance variables is also called a static variable, that is, a variable with static in front of the variable;
An instance variable is also called an object variable, that is, a variable that does not add static;
The difference is:
The difference between a class variable and an instance variable is that the class variable is common to all objects, where one object changes its value, the other object gets the changed result, and the instance variable is the object's private, and an object changes its value without affecting other objects;
Cases:
public class a{
static int a = 0; class variables
private int b = 0; Strength variable
}

public class b{
public void Main (string[] args) {
A a1 = new A ();
A a2 = new A ();
a1.a = 3; Equivalent to A.A = 3;
a1.b = 4;
System.out.println (a2.a); Result is 3
The class variable is for all objects, so A1 change a,a2 a also changes
System.out.println (a2.b); Result is 0
The instance only changes itself, so the B change of the A1 object does not affect the B variable of the object A2
}
}

The difference between a "Java" class variable and an instance variable

Related Article

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.