Difference between class variable and instance variable in java


Consider the following class:
public class IdentifyMyParts {
    public static int x = 7;
    public int y = 3;
} 
  1. Question: What are the class variables?
    Answer: x
  2. Question: What are the instance variables?
    Answer: y
  3. Question: What is the output from the following code:
    IdentifyMyParts a = new IdentifyMyParts(); 
    IdentifyMyParts b = new IdentifyMyParts(); 
    a.y = 5; 
    b.y = 6; 
    a.x = 1; 
    b.x = 2; 
    System.out.println("a.y = " + a.y); 
    System.out.println("b.y = " + b.y); 
    System.out.println("a.x = " + a.x); 
    System.out.println("b.x = " + b.x); 
    System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);
    
    Answer: Here is the output:
     a.y = 5 
     b.y = 6 
     a.x = 2 
     b.x = 2
     IdentifyMyParts.x = 2
    
    Becausexis defined as apublic static intin the classIdentifyMyParts, every reference toxwill have the value that was last assigned becausexis a static variable (and therefore a class variable) shared across all instances of the class. That is, there is only onex: when the value ofxchanges in any instance it affects the value ofxfor all instances ofIdentifyMyParts

No comments:

Post a Comment