Class Variables

Class variables are declared with static and have the concept of global variables. Class variables are used for the following purposes.

  • Object references and object attribute variables are created for each object as the object is created. However, class variables are created only once, regardless of the number of objects created from the class.
  • All objects created from one class share class variables.
  • Use class variables to communicate between objects or to express common properties of objects. Unlike object variables, class variables are accessed through the class name.
class Box {
  int width;
  int height;
  int depth;
  long idNum;
  //Class variable declaration
  static long boxID = 0;
  public Box() {
    //Increase the value of the class variable each time the constructor is executed
    //The idNum value of all objects created from the Box class will have a unique value depending on the order in which the objects are created.
    idNum = boxID++;
  }
}
Basic example of class variable 1
class Box {
  int width;
  int height;
  int depth;
  long idNum;
  static long boxID = 0;
  public Box() {
    idNum = boxID++;
  }
}

class StaticDemo {
  public static void main(String args[]) {
    Box mybox1 = new Box();
    Box mybox2 = new Box();
    Box mybox3 = new Box();
    Box mybox4 = new Box();
    System.out.println("id number of mybox1 : " + mybox1.idNum);
    System.out.println("id number of mybox2 : " + mybox2.idNum);
    System.out.println("id number of mybox3 : " + mybox3.idNum);
    System.out.println("id number of mybox4 : " + mybox4.idNum);
    System.out.println("The total number of boxes is " + Box.boxID);
  }
}
Basic example of class variable 2
public class StaticDemo1 {
  public static void main(String args[]) {
    int objectcount = Integer.parseInt(args[0]);
    //Array object array of Instance class type objectArray [] generated
    Instance objectArray[] = new Instance[objectcount];
    for(int i=0; i<objectcount; i++) {
      System.out.println(Instance.count + "번째 객체 생성") ;
    }
    System.out.println("The number of objects created is " +  Instance.count);
  }
}

class Instance {
  static int count = 0;
  Instance() {
    count++;
  }
}
Basic example of class variable 3

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Post