• Post Reply Bookmark Topic Watch Topic
  • New Topic

Weird Static method behavior  RSS feed

 
akbar pasha
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

May be I still don't get the sequence of how static methods are called and how class is loaded, but I stumbled across some strange behavior by static method. For your easy checking, I am copying the program here below. Can anyone tell me why the static method call to highID() always returns the number of objects that are instantiated?

class Vehicle {
int vID;
int speed;
int direction;
String owner;

private static int nextVID = 0;

Vehicle() {
vID = nextVID++;
}

Vehicle(String owner) {
this();
this.owner = owner;
}

static int highID() {
return nextVID;
}
};


public class VehicleDemo {

public static void main(String[] args) {


Vehicle v1 = new Vehicle();
v1.owner = "Shane";

Vehicle v2 = new Vehicle("Darcy");
Vehicle v3 = new Vehicle("Tom");

System.out.println("Vehicle v1 details:");
System.out.print(v1.owner + " " + v1.direction + " " + v1.speed + " " + v1.vID);
System.out.print(" " + Vehicle.highID() + "\n");
System.out.println("Vehicle v2 details:");
System.out.print(v2.owner + " " + v2.direction + " " + v2.speed + " " + v2.vID);
System.out.print(" " + Vehicle.highID() + "\n");
System.out.println("Vehicle v3 details:");
System.out.print(v3.owner + " " + v3.direction + " " + v3.speed + " " + v3.vID);
System.out.print(" " + Vehicle.highID() + "\n");
}
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is that nextVid is updated every time a constructor is called.
 
akbar pasha
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! I overlooked it. Got it now.
 
Ashwin Sharma
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi....
static variable are class variable, that means only one copy of it is kept with class, which can be used by all the instances.... Class is loded whenever reference to that class is made for the first time.... At that time all the static variables are loded and initialised.... You are incrementing the value of static variable in constructor which is called when new class is created thus thereby counting the number of instances of that class....
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!