Java 中的变量:
参考一:
There are several kinds of variables:
1.Member variables in a class—these are called fields.
2.Variables in a method or block of code—these are called local variables.
3.Variables in method declarations—these are called parameters.
参考二:
There are 4 types of variables in java.
1、Class variables
2、Instance variables
3、Local variables
4、Parameter Variables
PS、其中实例变量、类变量、常量都是属于成员变量的,成员变量又被称为全局变量,成员变量的范围比实例变量更宽泛。
Field Declaration Syntax
A Java field is declared using the following sysntax:
[access_modifier] [static] [finale] type name [= initial value];
PS. the Java field can be declared final or not. A final field cannot have its value changed. A final field must have an initial value assigned to it, and once set, the value cannot be changed again. A final field is often also declared static. A field declared static and final is also called a “constant”.
参考Java Fields
成员变量(member variables):
They are defined outside of any methods but inside the class and are used in different methods.
如果该成员变量有 static 关键字修饰,则该成员变量称为 静态变量 或 类变量,反之,被称为 非静态变量 或 实例变量。
局部变量(local variables):
方法内定义的变量、代码块中定义的变量,都属于局部变量。
1、不能使用static修饰局部变量,否则会出错,但是可以使用final修饰局部变量。
2、不同于类变量,局部变量必须在使用之前先声明。
3、局部变量没有默认初始值,因此,必须在使用之前为局部变量指定一个值。
参数变量(parameter variables):
They are defined as arguments to methods, constructors etc.
The difference between Parameter variable and local variable is that Parameter variables are always defined at signature of method or constructor while local variables are defined inside method or constructor
类变量/静态变量(class variables/static variables):
1. 可以向前引用
2. 变量属于类本身
3. 类变量不依赖类的实例,加载后存放在方法区,通过类名存取
4. 通过类的任意一个实例来访问类变量,底层都将将其转为通过类本身来访问类变量,它们的效果是一样的
5. 一旦类变量的值被改变,通过类或类的任意一个实例来访问类变量,得到的都将是被改变后的值
6. 将在类的初始化之前初始化
实例变量/非静态变量(instance variables/non-static variable)
1. 不能向前引用,如果向前引用,则称为非法向前引用,这是不允许的
2. 变量属于类的实例对象
3. 随着类的实例被创建而分配内存空间