10, the difference between static variables and instance variables?

1. From the grammatical difference:

        In front of a static variable to add the static keyword, but without the former instance variables

2. runtime difference:

       Instance variables belonging to the properties of an object, you must create an instance of an object, in which instance variables are allocated to the space,

In order to use this instance variable. Static variables do not belong to an instance of an object, but belong to the class, so called class variables, as long as the program is loaded

Bytecode class, do not create any instance of an object, static variables will be allocated to the space, static variables can be used.

In short, after the instance variables must create an object can be used by this object, you can use static variables directly reference the class name.

 

code show as below:

public class Test {
    
    public static int staticVar = 0;
    
    public int  instanceVar = 0;
    
    
    
    public Test(){
        
        staticVar++;
        
        instanceVar++;
        
        System.out.println("staticVar="+staticVar);
        
        System.out.println("instanceVar="+instanceVar);
        
    }
    
    public static void main(String[] args) {
           Test v =  new Test();
           Test v1 =  new Test();
           Test v3 =  new Test();
    }

}

 

Results are as follows:

staticVar=1
instanceVar=1
staticVar=2
instanceVar=1
staticVar=3
instanceVar=1

Code analysis:

No matter how many instances of objects (Test v = new Test ();) created, always only variable is assigned a staticVar

And each create an instance of the object, this will increase staticVar 1; however, create an instance of each object is allocated a instanceVar,

That is possible to assign a plurality instanceVar, and each value is only added once instanceVar

Guess you like

Origin www.cnblogs.com/helenwq/p/11648845.html