通常在一个class中,我们会构造变量variables。
variables
By kind
- Instance variable
-declared inside a class.(but not in a method.)
-they represent the "field" that each individual object has.
-live inside the objects they belong to.
当我们谈到class时,class不是object——class更像一个模板template,用来建立object。通过调用该class的构造函数constructor,我们可以得到objects。
public class Duck{
int size;
}
// Here, "size" is an instance variable;
// Every Duck has a "size" instance variable.
// Constructor
- Local variable
-declared inside of a method, including method parameters.
-只在method运行时存在。they are temporary, and live as long as the method is on the stack(not reaching the closing curly brace.)
public void foo(int x) { // parameter "x"
int i = x + 3;
boolean b = true; // i, b are local variables
}
By type
object reference / primitive reference
需要重点注意的是:
- 我们定义在一个class内部定义的都是reference variables, 是指向objects的遥控器,而不是objects。
Stack: live - Method invocations, Local variables (local variables). (比如go(), main())
Heap: live - ALL Objects live.