What are the differences between instance and class variables?

John Zukowski

Instance variables have separate values for each instance of a class. Class variables maintain a single shared value for all instances of the class, even if no instance object of that class exists.

You would use the static keyword to change an instance variable into a class variable.

Both instance and class variables are declared at the class level, not within methods:

public class Foo {
  static private int count; // class variable
  String name; // instance variable
  private void Bar() {
    int halfCount; // local variable
  }
}

Note also that classes are loaded by classloaders therefore class variables are unique on a per-classloader basis.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact