| 名称 | 修饰 | 访问 | 生命周期 |
|---|---|---|---|
| 全局变量(实例变量) | 无 static 修饰 | 对象名.变量名 | 只要对象被当作引用,实例变量就将存在 |
| 静态变量(类变量) | 用 static 修饰 | 类名.变量名或对象名.变量名 | 其生命周期取决于类的生命周期。类被垃圾回收机制彻底回收时才会被销毁 |
public class DataClass {
String name; // 成员变量、实例变量
int age; // 成员变量、实例变量
static final String website = "C语言中文网"; // 成员变量、静态变量(类变量)
static String URL = "http://c.biancheng.net"; // 成员变量、静态变量(类变量)
}
测试类代码如下所示:
public class Test {
public static void main(String[] args) {
// 创建类的对象
DataClass dc = new DataClass();
// 对象名.变量名调用实例变量(全局变量)
System.out.println(dc.name);
System.out.println(dc.age);
// 对象名.变量名调用静态变量(类变量)
System.out.println(dc.website);
System.out.println(dc.URL);
// 类名.变量名调用静态变量(类变量)
System.out.println(DataClass.website);
System.out.println(DataClass.URL);
}
}
public class Test2 {
public static void main(String[] args) {
int a = 7;
if (5 > 3) {
int s = 3; // 声明一个 int 类型的局部变量
System.out.println("s=" + s);
System.out.println("a=" + a);
}
System.out.println("a=" + a);
}
}
上述实例中定义了 a 和 s 两个局部变星,其中 int 类型的 a 的作用域是整个 main() 方法,而 int 类型的变量 s 的作用域是 if 语句的代码块内,其执行结果如图 2 所示:
public class Test3 {
public static void testFun(int n) {
System.out.println("n=" + n);
}
public static void main(String[] args) {
testFun(3);
}
}
在上述实例中定义了一个 testFun() 方法,该方法中包含一个 int 类型的参数变量 n,其作用域是 testFun() 方法体内。当调用方法时传递进了一个参数 3,因此其输出控制台的 n 值是 3。
public class Test4 {
public static void test() {
try {
System.out.println("Hello!Exception!");
} catch (Exception e) { // 异常处理块,参数为 Exception 类型
e.printStackTrace();
}
}
public static void main(String[] args) {
test();
}
}
在上述实例中定义了异常处理语句,异常处理块 catch 的参数为 Exception 类型的变量 e,作用域是整个 catch 块。
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有