Static and Instance Variable

Question: What is the difference between static variable and instance variable?

Answer:

public class Thanh{
int x = 9;
}
....
Thanh a = new Thanh();
Thanh b = new Thanh();

Both a & b have its own copy of x

---------------------------------------------

public class Thanh{
static int x = 9;
}
....
Thanh a = new Thanh();
Thanh b = new Thanh();

Both a & b have the exactly one x to share between them


Note: the static variable is initialized immediately when the JVM loads the class


No Response to "Static and Instance Variable"

Post a Comment

 

Copyright © 2013-2014 Lai Duy Thanh All rights reserved.