Java member variables and local variables
Article Directory
1 Similarities
1.1 The format of defining variables is the same
变量类型 变量名 = 变量值
1.2 are declared before use
1.3 Variables have their scope (the scope is a pair of braces)
2 Differences
2.1 position in the class declaration
Attributes: directly defined in {}
Local variables: declared in method, method parameter, code block, constructor parameter, constructor
class Person{
/*
这两个是成员变量
*/
String name;
int age;
public void eat(String name //局部变量){
int number; //局部变量
}
}
2.2 Competence modifier
Attribute: You can specify its permissions when you declare, use permission modifiers (including public private and default protected)
Local variables: permission modifiers cannot be used (there can be two understandings, one is that they cannot be written, and the other is that local variables and method permission modifiers are the same)
class Person{
/*
成员变量定义时可以指明权限修饰符
*/
private String name;
public int age;
public void eat(){
//private int age; 局部变量定义时不能指明权限修饰符
}
}
About 2.3 default initialization
Attributes: For the attributes of the class, there are default initialization values according to its type
The integer type is 0, the floating type is 0.0, char is 0, boolean is false, and the reference data type is null
Local variables: no default initialization values mean : Before calling a local variable assignment must show special : parameter assignment when you call on the line
2.4 is loaded in memory location
Attributes: loaded into the heap space (non-static)
Local variables: loaded into the stack space