If static variables belong to the class and NOT part of the object then how come we are able to invoke it with an object reference variable and also modify its value.
class AQ { static int t = 6; int g = 10; } class Tr { public static void main(String[] args) { AQ q = new AQ(); System.out.println(q.t); q.t = 5; System.out.println(q.t); new Tr().call(); } void call() { System.out.println(new AQ().t); } }Output:655That is allowed in Java. But be careful.
If you use an object reference to call a static method in a class definition, then it does not matter which object reference you use, even if that reference is null.
Only the type of the reference is considered.
class Ts {
public static void main(String[] args) {
// AQ q = new AQ(); // 1
AQ q = null; // 2
System.out.println(q.t);
}
}
Output:
6
[With 2(q = null) - If you invoke the static variable we will not get any exception where as if we invoke instance variable like q.g we will get java.lang.NullPointerException.]
Here the output is 6 because it's a totally new class called Ts where we are instantiating the class AQ. Hence it reflects the value 6 with which class variable(static) t has been initialized with in class AQ.
Once you initialize a class(static) variable with a new value with in your class using the reference variable of the external class and if you access the same variable with a new instance of the external class still you get to see the same value that has been set with in your class and NOT the value that has been initialized with in the external class.
This is because static variables are accessed based on class(reference) type and NOT Object type.
Static variables are initialized at the class loading time, instance variables are initialized before a constructor is executed.
What is the difference between class variables and instance variables ?
The difference is that no matter what instance of an object you use, you can change the class variables. It doesn't have anything to do with an instance.
However, you can only access an instance variable with a particular instance.
code: class AQ { static int t = 6; int g = 10; } class Tr { public static void main(String[] args) { AQ q = new AQ(); System.out.println(q.t); System.out.println(q.g); q.t = 5; q.g = 123; System.out.println(q.t); System.out.println(q.g); new Tr().call(); } void call() { System.out.println(new AQ().t); System.out.println(new AQ().g); } } Output:6105123510