1.public 公共变量
由public修饰的变量称为公共变量,可被任何包中的任何类访问,只有在确认任何外部访问都不会带来不良后果的情况下才将成员声明为公共的。公共变量对任何类都是可见的,因此它没有秘密可言,不具有数据保护功能。
2.private私有变量
由private修饰的变量称为私有变量,只能被声明它的类所使用,拒绝任何外部类的访问。私有变量是不公开的,它们得到了最好的保护,这是对类进行封装时使用的主要方法。
3.static 静态变量,也称为类变量。非静态变量称为实例变量。
需求:每次使用new关键字创建对象,系统都会为每个对象分配存储空间,如果希望某些特定的数据在内存中只有一份,而且能被一个类的所有对象共享,就使用static修饰。
例3:设计一个Student类,如下所示,该校所有学生共享学校名称。
class Student {
static String schoolName; // 定义静态变量schoolName
}
public class Example12 {
public static void main(String[] args) {
Student stu1 = new Student(); // 创建学生对象
Student stu2 = new Student();
Student.schoolName = "大连电子学校"; // 为静态变量赋值
System.out.println("我的学校是" + stu1.schoolName); // 打印第一个学生对象的学校
System.out.println("我的学校是" + stu2.schoolName); // 打印第二个学生对象的学校
}
}
访问方法:
- 对象名.成员变量名
- 类名.成员变量名
4.final 最终变量
一旦成员变量被声明为final,在程序运行中将不能被改变。这样的成员变量就是一个常量。
例如:final double PI=3.14159;
如果在后面试图重新对它赋值,将产生编译错误。
例4-1:阅读下面程序,输出结果是什么?
public class Example08 {
public static void main(String[] args) {
final int num = 2; // 第一次可以赋值
num = 4; // 再次赋值会报错
}
}
例4-2:阅读下面程序,输出结果是什么?
/ 定义Student类
class Student {
final String name; // 使用final关键字修饰name属性
// 定义introduce()方法,打印学生信息
public void introduce() {
System.out.println("我是一个学生,我叫" + name);
}
}
// 定义测试类
public class Example09 {
public static void main(String[] args) {
Student stu = new Student(); // 创建Student类的实例对象
stu.introduce(); // 调用Student的introduce()方法
}
}
注意:使用final修饰成员变量,虚拟机不会对其进行初始化。