1. static修饰成员变量
特点:被所有的类所共享
JavaBean:
public class Student {
static String teacherName;
String name;
int age;
}
Test:
public class Test {
public static void main(String[] args) {
Student stu1 = new Student();
stu1.name = "小明";
stu1.age = 18;
Student.teacherName = "阿伟老师";
Student stu2 = new Student();
stu2.name = "小红";
stu2.age = 19;
System.out.println("学生1的信息:" + stu1.name + "," + stu1.age + "," + Student.teacherName);
System.out.println("学生2的信息:" + stu2.name + "," + stu2.age + "," + Student.teacherName);
}
}
输出结果:
学生1的信息:小明,18,阿伟老师
学生2的信息:小红,19,阿伟老师
可见只需要更改一次(推荐使用类名更改): 所有的对象都进行共享这个静态变量;
Student.teacherName = "阿伟老师";
**什么时候使用呢? **
- 当这个属性被大家所共用: 饮水机 大学老师
2. static的内存解析
- 静态变量是随着类的加载而加载的,是优先于对象出现的:加载Memory.class的时候就在堆内存开辟出了静态空间了。
- 静态对象不属于对象,属于类 --> 用类名调用
- 创建对象的时候,所有对象都会记录静态区的值,所有的对象都共享同一份数据。
- 同样,当main方法结束后,对象随之消失; 但是静态区和方法区都是随着编辑器的结束而结束!
3. static修饰的成员方法
static修饰的方法叫做静态方法 该方法多用在测试类和工具类中。
工具类:帮助我们做一些事情的类:
- 遍历数组
- 求最大值
- 求最小值
下面为示例:
测试类:
public class Test {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
String res = ArrayUtil.printArray(arr);
System.out.println(res);
double avg = ArrayUtil.averageArray(arr);
System.out.println(avg);
}
}
工具类:
public class ArrayUtil {
//私有构造方法,不让外界创建对象
private ArrayUtil() {
}
//公有静态方法,让外界调用
public static String printArray(int[] arr) {
String result = "[";
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
result += arr[i] + "]";
} else {
result += arr[i] + ",";
}
}
return result;
}
public static double averageArray(int[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
}
输出:
[1,2,3,4,5]
3.0