i am just curious why class variable (i.e variables with
static keyword) its called class variable instead of package variable. I mean if I declare a static variable in one class, i can access this variable from another class in the same package as long as it is not private.
Also, instance variables are declared inside a class and methods in that class can access instance variables, why not name them class variables… I just don’t get it.
The class is basically the frame or blueprint for creating instances (objects). Static variables and methods are defined inside the frame and created when the class is loaded by the ClassLoader, so no instance needs to be created for them to exist. That’s why they are class variables. They are not package variables because they belong specifically to that class. I.e. you would access them by calling MyClass.myVariable.
Instance variables only come into existence when an instance of the class i.e. an object is created by calling new(), and they are specific to that object and not specific to the class. There are as many counts of an instance variable as the number of objects of that class are created, whereas there is always just one count of the static class variable. That is why they are called instance variables, because they are specific to an instance and not to the class.