Contrast members and local variables are different:
-
1. Define the position is not the same] [Key memory
local variables: define within the method.
Member variables: directly defined in the class which , outside methods. -
2. The memory location is not the same
local variables: memory stack, stack.
Member variables: in heap memory, heap. It is used when the new constructor. -
3. The life cycle is not the same as
local variables: With the push method with the emergence of the stack with the method disappear.
Member variables: With the emergence of object is created, with the object is recovered JVM disappear. -
4. The default value is not the same as [Memory] Key
local variables: no default , must be assigned before you can use.
Member variables: If there is no assignment, there will be a default value.
public class Demo05Variables {
String name; //成员变量
public void method(int param) { //成员方法的参数也是一个局部变量
int num = 10;//局部变量
}
}