简体   繁体   中英

naming practice of variables in java. why class variable not package variable

i am just curious why class variable (ie 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. Ie you would access them by calling MyClass.myVariable.

Instance variables only come into existence when an instance of the class ie 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.

It's called class variable because it is inside a Class. Visibility doesn't matter in the naming convention. And a non-static variable is a instance variable because it can be different among instances of a class. A Method is always the same among all the instances of that class.

Because packages consist of groups of classes working together, whereas classes are the abstractions that make up the objects in the implementation. You cannot have variables exist purely as package variables because it wouldn't give a context for which class "owns" the variable. Plus, it's just bad Object Oriented Programming.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM