通常在一個class中,我們會構(gòu)造變量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.
當(dāng)我們談到class時,class不是object——class更像一個模板template救鲤,用來建立object材泄。通過調(diào)用該class的構(gòu)造函數(shù)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運(yùn)行時存在参滴。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
需要重點(diǎn)注意的是:
- 我們定義在一個class內(nèi)部定義的都是reference variables, 是指向objects的遙控器,而不是objects锻弓。
Stack: live - Method invocations, Local variables (local variables). (比如go(), main())
Heap: live - ALL Objects live.