变量
根据官方文档,Java语言定义了以下几种不同类型的变量:
- Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the
statickeyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); thecurrentSpeedof one bicycle is independent from thecurrentSpeedof another. - Class Variables (Static Fields) A class variable is any field declared with the
staticmodifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked asstaticsince conceptually the same number of gears will apply to all instances. The codestatic int numGears = 6;would create such a static field. Additionally, the keywordfinalcould be added to indicate that the number of gears will never change. - Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example,
int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. - Parameters You've already seen examples of parameters, both in the
Bicycleclass and in themainmethod of the "Hello World!" application. Recall that the signature for themainmethod ispublic static void main(String[] args). Here, theargsvariable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the tutorial.
分别是实例变量(非静态字段),类变量(静态字段), 局部变量和参数。其中,类变量(静态字段)通过 static 关键字修饰,还可以添加 final 关键字以表明该变量的值永远不变。对于局部变量,并没有特殊的关键字来指明该变量是局部的。对于局部变量的定义完全是由该变量定义的位置所决定的,一般在方法体中声明的变量我们称之为局部变量。
对于初学者,通常我们会对变量和字段这两种表述方式感到疑惑,因为大多数情况下,两者实际上指向的是同一种东西。根据每个人的习惯不同,表述有所不同。一般来说,对两者的表述根据我们关注的“对象”而有所不同。当我们说变量的时候,通常我们关注的是变量本身,比如说,“我要定义一个变量”,不管是实例变量、类变量还是局部变量,这个时候通常我们称之为变量。而当我们关注的”对象“是一个object(对象时候),比如说,“这个object(对象)有哪些字段”,则通常叫做字段。因为我们知道,object(对象)将它们各自的状态存在字段中,这个时候我们更关心的是这个对象拥有哪些状态或属性而不是这个变量本身。
命名规则
变量的命名是区别大小写的,可以是以字母、$、_开头的一组无限长度的Unicode字符和数字。但是通常在实际编程中,我们要避免以$、_符号开头,并且在变量命名中永远不要使用$符号,尽管在某些自动生成的名字中会包含$符号。如果变量名是单个单词,通常是小写的,如果是以多个单词组成,则后续单词的第一个字母要大写。比如 int currentGear = 6。如果这个变量是一个常量,则要全部大写,如果是由多个单词组成,则以下划线 "_" 分割, 例如 static final int NUM_GEARS = 6。