Java 引用变量
原文: https://javabeginnerstutorial.com/core-java-tutorial/java-reference-variable/
引用变量用于引用对象。 它们以无法更改的特定类型声明。
引用变量的类型
- 静态变量
- 实例变量
- 方法参数
- 局部变量
静态变量示例
class test {
//below variable is static variable means it is class level variable
static int i;
public static void main(String[] args) {
// As i is an static variable it can be accessed directly without using any object
System.out.println("Value before calling method1: " + i);
test t1 = new test();
t1.method1();
System.out.println("Value after calling method1: " + i);
t1.method2();
System.out.println("Value after calling method2: " + i);
}
void method1() {
i++;
}
void method2() {
i++;
}
}
实例/局部/方法参数示例
class MPE {
// Instance Variable
int i;
public static void main(String[] args) {
/*
* Here i is an Instance variable.
*/
test t1 = new test();
System.out.println("Value before calling method1: " + t1.i);
}
/*
* Here j is a method parameter. And k is a local variable.
*
* Note**: Local variables life is only till the end of method
*/
void method1(int j) {
int k;
i = j;
/*
* Local Variable(k)'s life ends once execution for this method
* completes. As k is local is variable it needs to be initialized
* before we can use it. But as it is not getting used here, it can stay here without initializing
*/
}
}