Variables in Java 变量

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容