Variables in Java 變數

weixin_34138377發表於2018-01-17

通常在一個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.

相關文章