简体   繁体   English

java中变量的命名实践。 为什么类变量不是包变量

[英]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.我只是好奇为什么类变量(即带有static关键字的变量)被称为类变量而不是包变量。 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.也就是说,您可以通过调用 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.实例变量仅在类的实例(即通过调用 new() 创建对象)时才存在,并且它们特定于该对象而不是特定于类。 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.另外,它只是糟糕的面向对象编程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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